instruction
stringclasses
100 values
code
stringlengths
78
193k
response
stringlengths
259
170k
file
stringlengths
59
203
Document classes and their methods
# -*- coding: utf-8 -*- from __future__ import annotations import os import signal import subprocess import sys import time from pathlib import Path from typing import Optional import click from .process_utils import ( _is_copaw_wrapper_process, _process_table, _windows_process_snapshot, ) _PROJECT_ROO...
--- +++ @@ -25,12 +25,14 @@ def _backend_port(ctx: click.Context, port: Optional[int]) -> int: + """Resolve backend port from explicit option or global CLI context.""" if port is not None: return port return int((ctx.obj or {}).get("port", 8088)) def _listening_pids_for_port(port: int) ->...
https://raw.githubusercontent.com/agentscope-ai/CoPaw/HEAD/src/copaw/cli/shutdown_cmd.py
Help me document legacy Python code
# -*- coding: utf-8 -*- import json import logging import threading from datetime import date, timedelta from pathlib import Path import aiofiles from pydantic import BaseModel, Field from ..constant import WORKING_DIR, TOKEN_USAGE_FILE logger = logging.getLogger(__name__) class TokenUsageStats(BaseModel): p...
--- +++ @@ -1,4 +1,5 @@ # -*- coding: utf-8 -*- +"""Token usage manager""" import json import logging @@ -15,6 +16,7 @@ class TokenUsageStats(BaseModel): + """Prompt/completion tokens and call count.""" prompt_tokens: int = Field(0, ge=0) completion_tokens: int = Field(0, ge=0) @@ -22,6 +24,7 @@ ...
https://raw.githubusercontent.com/agentscope-ai/CoPaw/HEAD/src/copaw/token_usage/manager.py
Add docstrings to existing functions
# -*- coding: utf-8 -*- from __future__ import annotations from enum import Enum from typing import TYPE_CHECKING if TYPE_CHECKING: from .models import ToolGuardResult class ApprovalDecision(str, Enum): APPROVED = "approved" DENIED = "denied" TIMEOUT = "timeout" def format_findings_summary( r...
--- +++ @@ -1,4 +1,5 @@ # -*- coding: utf-8 -*- +"""Approval helpers for tool-guard mediated tool execution.""" from __future__ import annotations from enum import Enum @@ -9,6 +10,7 @@ class ApprovalDecision(str, Enum): + """Possible approval outcomes for a guarded tool call.""" APPROVED = "approved"...
https://raw.githubusercontent.com/agentscope-ai/CoPaw/HEAD/src/copaw/security/tool_guard/approval.py
Generate docstrings with examples
# -*- coding: utf-8 -*- from __future__ import annotations import logging import threading from typing import Any, Optional from .schema import BackendType, LocalModelInfo from .manager import get_local_model from .backends.base import LocalBackend from .chat_model import LocalChatModel logger = logging.getLogger(_...
--- +++ @@ -1,4 +1,5 @@ # -*- coding: utf-8 -*- +"""Singleton factory for local model instances.""" from __future__ import annotations @@ -21,6 +22,7 @@ def get_active_local_model() -> ( Optional[tuple[Optional[str], LocalBackend]] | None ): + """Return (model_id, backend) if a local model is currently lo...
https://raw.githubusercontent.com/agentscope-ai/CoPaw/HEAD/src/copaw/local_models/factory.py
Add docstrings with type hints explained
# -*- coding: utf-8 -*- from __future__ import annotations import json from pathlib import Path from typing import Optional import click from .http import client, print_json from ..app.channels.schema import DEFAULT_CHANNEL def _base_url(ctx: click.Context, base_url: Optional[str]) -> str: if base_url: ...
--- +++ @@ -1,4 +1,5 @@ # -*- coding: utf-8 -*- +"""CLI commands for managing chats via HTTP API (/chats).""" from __future__ import annotations import json @@ -12,6 +13,11 @@ def _base_url(ctx: click.Context, base_url: Optional[str]) -> str: + """Resolve base_url with priority: + 1) command --base-url + ...
https://raw.githubusercontent.com/agentscope-ai/CoPaw/HEAD/src/copaw/cli/chats_cmd.py
Auto-generate documentation strings for this file
# -*- coding: utf-8 -*- from __future__ import annotations import logging import re from dataclasses import dataclass, field from pathlib import Path from typing import Any import yaml logger = logging.getLogger(__name__) _MAX_PATTERN_LENGTH = 1000 # Where the built-in default policy lives (ships with the package)...
--- +++ @@ -1,4 +1,26 @@ # -*- coding: utf-8 -*- +"""Scan policy: org-customisable allowlists and rule scoping. + +Every organisation has a different security bar. A ``ScanPolicy`` +captures what counts as benign, which rules fire on which file +types, which credentials are test-only, and so on. + +Usage +----- + f...
https://raw.githubusercontent.com/agentscope-ai/CoPaw/HEAD/src/copaw/security/skill_scanner/scan_policy.py
Document my Python code with docstrings
# -*- coding: utf-8 -*- from __future__ import annotations import json from pathlib import Path from typing import Optional import click from .http import client, print_json from ..app.channels.schema import DEFAULT_CHANNEL def _base_url(ctx: click.Context, base_url: Optional[str]) -> str: if base_url: ...
--- +++ @@ -12,6 +12,11 @@ def _base_url(ctx: click.Context, base_url: Optional[str]) -> str: + """Resolve base_url with priority: + 1) command --base-url + 2) global --host/--port + (already resolved in main.py, may come from config.json) + """ if base_url: return base_url.rstrip("...
https://raw.githubusercontent.com/agentscope-ai/CoPaw/HEAD/src/copaw/cli/cron_cmd.py
Add detailed docstrings explaining each function
# -*- coding: utf-8 -*- from __future__ import annotations import logging from pathlib import Path from typing import Any, Iterator, Optional, Type from pydantic import BaseModel from .base import LocalBackend logger = logging.getLogger(__name__) def _normalize_messages(messages: list[dict]) -> list[dict]: o...
--- +++ @@ -1,4 +1,5 @@ # -*- coding: utf-8 -*- +"""MLX backend using mlx-lm for Apple Silicon.""" from __future__ import annotations @@ -14,6 +15,11 @@ def _normalize_messages(messages: list[dict]) -> list[dict]: + """Normalise messages for MLX tokenizer chat templates. + + * Content must be a plain str...
https://raw.githubusercontent.com/agentscope-ai/CoPaw/HEAD/src/copaw/local_models/backends/mlx_backend.py
Add well-formatted docstrings
# -*- coding: utf-8 -*- from __future__ import annotations import os from typing import Any, List try: import ollama except ImportError: ollama = None # type: ignore from agentscope.model import ChatModelBase from copaw.providers.provider import ModelInfo, Provider class OllamaProvider(Provider): d...
--- +++ @@ -1,4 +1,5 @@ # -*- coding: utf-8 -*- +"""An OpenAI provider implementation.""" from __future__ import annotations @@ -16,6 +17,7 @@ class OllamaProvider(Provider): + """Provider implementation for Ollama local LLM hosting platform.""" def model_post_init(self, __context: Any) -> None: ...
https://raw.githubusercontent.com/agentscope-ai/CoPaw/HEAD/src/copaw/providers/ollama_provider.py
Add standardized docstrings across the file
# -*- coding: utf-8 -*- from __future__ import annotations from typing import List from pydantic import BaseModel, Field class ModelInfo(BaseModel): id: str = Field(..., description="Model identifier used in API calls") name: str = Field(..., description="Human-readable model name") class ProviderDefinit...
--- +++ @@ -1,4 +1,5 @@ # -*- coding: utf-8 -*- +"""Pydantic data models for providers and models.""" from __future__ import annotations @@ -13,6 +14,7 @@ class ProviderDefinition(BaseModel): + """Static definition of a provider (built-in or custom).""" id: str = Field(..., description="Provider iden...
https://raw.githubusercontent.com/agentscope-ai/CoPaw/HEAD/src/copaw/providers/models.py
Write docstrings for this repository
# -*- coding: utf-8 -*- from __future__ import annotations import logging from typing import Any, Iterator, Optional, Type from pydantic import BaseModel from .base import LocalBackend logger = logging.getLogger(__name__) def _normalize_messages(messages: list[dict]) -> list[dict]: out: list[dict] = [] f...
--- +++ @@ -1,4 +1,5 @@ # -*- coding: utf-8 -*- +"""llama.cpp backend using llama-cpp-python.""" from __future__ import annotations @@ -13,6 +14,11 @@ def _normalize_messages(messages: list[dict]) -> list[dict]: + """Normalise messages for llama-cpp-python's Jinja chat templates. + + * Content must be a ...
https://raw.githubusercontent.com/agentscope-ai/CoPaw/HEAD/src/copaw/local_models/backends/llamacpp_backend.py
Document functions with detailed explanations
# -*- coding: utf-8 -*- from datetime import date from typing import Any, AsyncGenerator, Literal, Type from agentscope.model import ChatModelBase from agentscope.model._model_response import ChatResponse from agentscope.model._model_usage import ChatUsage from pydantic import BaseModel from .manager import get_toke...
--- +++ @@ -1,4 +1,5 @@ # -*- coding: utf-8 -*- +"""Model wrapper that records token usage from LLM responses.""" from datetime import date from typing import Any, AsyncGenerator, Literal, Type @@ -12,6 +13,7 @@ class TokenRecordingModelWrapper(ChatModelBase): + """Wraps a ChatModelBase to record token usage...
https://raw.githubusercontent.com/agentscope-ai/CoPaw/HEAD/src/copaw/token_usage/model_wrapper.py
Add docstrings to my Python code
# -*- coding: utf-8 -*- from __future__ import annotations from abc import ABC, abstractmethod from typing import Any from ..models import GuardFinding class BaseToolGuardian(ABC): def __init__(self, name: str) -> None: self.name = name # -----------------------------------------------------------...
--- +++ @@ -1,4 +1,11 @@ # -*- coding: utf-8 -*- +"""Abstract base class for all tool-call guardians. + +Every guardian must subclass :class:`BaseToolGuardian` and implement +:meth:`guard`. The interface is intentionally minimal so that new +detection engines (e.g. LLM-based, semantic analysis) can be added +as drop-i...
https://raw.githubusercontent.com/agentscope-ai/CoPaw/HEAD/src/copaw/security/tool_guard/guardians/__init__.py
Add docstrings including usage examples
# -*- coding: utf-8 -*- from __future__ import annotations from dataclasses import dataclass, field from datetime import datetime, timezone from enum import Enum from typing import Any # Memory mark attached to tool-guard denied messages so they can be # identified and cleaned up across modules (react_agent, runner,...
--- +++ @@ -1,4 +1,10 @@ # -*- coding: utf-8 -*- +"""Data models for tool-call guarding. + +These models are intentionally separate from the skill-scanner models so +that the two sub-systems can evolve independently while sharing the same +conceptual vocabulary (severity, threat category, finding, result). +""" from _...
https://raw.githubusercontent.com/agentscope-ai/CoPaw/HEAD/src/copaw/security/tool_guard/models.py
Write clean docstrings for readability
# -*- coding: utf-8 -*- from __future__ import annotations import logging from datetime import datetime from typing import List, Optional, Union from pydantic import BaseModel, Field, field_validator from ..constant import MODEL_PROVIDER_CHECK_TIMEOUT logger = logging.getLogger(__name__) class OllamaModelInfo(Bas...
--- +++ @@ -1,4 +1,10 @@ # -*- coding: utf-8 -*- +"""Ollama model management using the Ollama Python SDK. + +This module mirrors the structure of local_models.manager, but delegates all +lifecycle operations to the running Ollama daemon instead of managing files +or a manifest.json. Ollama remains the single source of ...
https://raw.githubusercontent.com/agentscope-ai/CoPaw/HEAD/src/copaw/providers/ollama_manager.py
Fully document this Python code with docstrings
from fastapi import FastAPI, Request from fastapi.responses import StreamingResponse from ag_ui.core import RunAgentInput from ag_ui.encoder import EventEncoder from .agent import StrandsAgent def add_strands_fastapi_endpoint( app: FastAPI, agent: StrandsAgent, path: str, **kwargs ) -> None: ...
--- +++ @@ -1,3 +1,4 @@+"""FastAPI endpoint utilities for AWS Strands integration.""" from fastapi import FastAPI, Request from fastapi.responses import StreamingResponse @@ -11,9 +12,11 @@ path: str, **kwargs ) -> None: + """Add a Strands agent endpoint to FastAPI app.""" @app.post(path) ...
https://raw.githubusercontent.com/ag-ui-protocol/ag-ui/HEAD/integrations/aws-strands/python/src/ag_ui_strands/endpoint.py
Generate docstrings for exported functions
from enum import Enum from typing import Annotated, Any, List, Literal, Optional, Union from pydantic import Field from .types import ConfiguredBaseModel, Message, State, Role, RunAgentInput # Text messages can have any role except "tool" TextMessageRole = Literal["developer", "system", "assistant", "user"] class...
--- +++ @@ -1,3 +1,6 @@+""" +This module contains the event types for the Agent User Interaction Protocol Python SDK. +""" from enum import Enum from typing import Annotated, Any, List, Literal, Optional, Union @@ -11,6 +14,9 @@ class EventType(str, Enum): + """ + The type of event. + """ TEXT_MES...
https://raw.githubusercontent.com/ag-ui-protocol/ag-ui/HEAD/sdks/python/ag_ui/core/events.py
Generate docstrings with examples
# src/__init__.py from __future__ import annotations import logging import os from typing import Dict, Iterable from .adk_agent import ADKAgent from .event_translator import EventTranslator, adk_events_to_messages from .session_manager import SessionManager, CONTEXT_STATE_KEY, INVOCATION_ID_STATE_KEY from .endpoint...
--- +++ @@ -1,5 +1,9 @@ # src/__init__.py +"""ADK Middleware for AG-UI Protocol + +This middleware enables Google ADK agents to be used with the AG-UI protocol. +""" from __future__ import annotations @@ -31,6 +35,7 @@ def _configure_logging_from_env() -> None: + """Configure component loggers based on en...
https://raw.githubusercontent.com/ag-ui-protocol/ag-ui/HEAD/integrations/adk-middleware/python/src/ag_ui_adk/__init__.py
Add documentation for all methods
#!/usr/bin/env python3 import re import sys import tomllib from pathlib import Path # Ordered: ag-ui-protocol (no internal deps) first. PACKAGES = [ "sdks/python", "integrations/langgraph/python", "integrations/crew-ai/python", "integrations/agent-spec/python", "integrations/adk-middleware/python"...
--- +++ @@ -1,4 +1,21 @@ #!/usr/bin/env python3 +""" +Rewrites pyproject.toml files in-place for preview publishing to TestPyPI. + +Usage: + python scripts/rewrite-python-preview-versions.py 0.0.0.dev1741617123 + +For each package in PACKAGES: + - Rewrites the package version to the given preview version + - Rewri...
https://raw.githubusercontent.com/ag-ui-protocol/ag-ui/HEAD/scripts/rewrite-python-preview-versions.py
Help me write clear docstrings
from dataclasses import dataclass from typing import Any, Awaitable, Callable from langchain.agents.middleware import AgentMiddleware, ModelRequest from langchain_core.messages import ToolMessage from langchain_core.runnables.config import ensure_config, var_child_runnable_config def _with_intermediate_state(config:...
--- +++ @@ -1,3 +1,6 @@+""" +Custom middleware helpers for ag-ui LangGraph agents. +""" from dataclasses import dataclass from typing import Any, Awaitable, Callable @@ -25,6 +28,14 @@ ] def _is_pre_tool_call(self, request: ModelRequest) -> bool: + """Return True if this model call precedes a ...
https://raw.githubusercontent.com/ag-ui-protocol/ag-ui/HEAD/integrations/langgraph/python/ag_ui_langgraph/middlewares/state_streaming.py
Create documentation strings for testing functions
# src/ag_ui_adk/client_proxy_tool.py import asyncio import json import uuid import inspect from typing import Any, Optional, List, Dict, Set import logging from google.adk.tools import BaseTool, LongRunningFunctionTool from google.genai import types from ag_ui.core import Tool as AGUITool, EventType from ag_ui.core ...
--- +++ @@ -1,5 +1,6 @@ # src/ag_ui_adk/client_proxy_tool.py +"""Client-side proxy tool implementation for AG-UI protocol tools.""" import asyncio import json @@ -25,6 +26,14 @@ class ClientProxyTool(BaseTool): + """A proxy tool that bridges AG-UI protocol tools to ADK. + + This tool appears as a normal...
https://raw.githubusercontent.com/ag-ui-protocol/ag-ui/HEAD/integrations/adk-middleware/python/src/ag_ui_adk/client_proxy_tool.py
Add docstrings for utility scripts
import copy import asyncio from typing import List, Optional from fastapi import FastAPI, Request from fastapi.responses import StreamingResponse from crewai.utilities.events import ( FlowStartedEvent, FlowFinishedEvent, MethodExecutionStartedEvent, MethodExecutionFinishedEvent, ) from crewai.flow.flow...
--- +++ @@ -1,3 +1,6 @@+""" +AG-UI FastAPI server for CrewAI. +""" import copy import asyncio from typing import List, Optional @@ -49,6 +52,7 @@ async def create_queue(flow: object) -> asyncio.Queue: + """Create a queue for a flow.""" queue_id = id(flow) async with QUEUES_LOCK: queue = asy...
https://raw.githubusercontent.com/ag-ui-protocol/ag-ui/HEAD/integrations/crew-ai/python/ag_ui_crewai/endpoint.py
Insert docstrings into my code
from typing import Dict, Any, List, Optional, Union from enum import Enum from pydantic import BaseModel class StrandsEventTypes(str, Enum): MESSAGE_START = "message_start" MESSAGE_CONTENT = "message_content" MESSAGE_END = "message_end" TOOL_CALL_START = "tool_call_start" TOOL_CALL_END = "tool_cal...
--- +++ @@ -1,9 +1,11 @@+"""Type definitions for AWS Strands integration.""" from typing import Dict, Any, List, Optional, Union from enum import Enum from pydantic import BaseModel class StrandsEventTypes(str, Enum): + """Event types for Strands streaming.""" MESSAGE_START = "message_start" MESSAG...
https://raw.githubusercontent.com/ag-ui-protocol/ag-ui/HEAD/integrations/aws-strands/python/src/ag_ui_strands/types.py
Help me add docstrings to my project
from __future__ import annotations import contextvars from contextlib import contextmanager from functools import wraps from typing import Any, Awaitable, Callable, Concatenate, Dict, List, Literal, Optional, ParamSpec, TypeVar from ag_ui.core import RunAgentInput from ag_ui_agentspec.agentspec_tracing_exporter impor...
--- +++ @@ -19,6 +19,13 @@ @contextmanager def _inject_missing_contextvars(base_context: contextvars.Context): + """ + Apply ContextVars captured during agent construction to the current task context. + + This is intentionally additive: only ContextVars that are *missing* from the current + context are i...
https://raw.githubusercontent.com/ag-ui-protocol/ag-ui/HEAD/integrations/agent-spec/python/ag_ui_agentspec/agent.py
Document helper functions with docstrings
from typing import Annotated, Any, Dict, List, Literal, Optional, Union from pydantic import BaseModel, ConfigDict, Field, model_validator from pydantic.alias_generators import to_camel class ConfiguredBaseModel(BaseModel): model_config = ConfigDict( extra="allow", alias_generator=to_camel, ...
--- +++ @@ -1,3 +1,6 @@+""" +This module contains the types for the Agent User Interaction Protocol Python SDK. +""" from typing import Annotated, Any, Dict, List, Literal, Optional, Union @@ -6,6 +9,9 @@ class ConfiguredBaseModel(BaseModel): + """ + A configurable base model. + """ model_config ...
https://raw.githubusercontent.com/ag-ui-protocol/ag-ui/HEAD/sdks/python/ag_ui/core/types.py
Document classes and their methods
import json import re from enum import Enum from pydantic import TypeAdapter from pydantic_core import PydanticSerializationError from typing import List, Any, Dict, Union from dataclasses import is_dataclass, asdict, fields from datetime import date, datetime from langchain_core.messages import BaseMessage, HumanMes...
--- +++ @@ -48,6 +48,7 @@ return json.dumps(item) def convert_langchain_multimodal_to_agui(content: List[Dict[str, Any]]) -> List[Union[TextInputContent, BinaryInputContent]]: + """Convert LangChain's multimodal content to AG-UI format.""" agui_content = [] for item in content: if isinstanc...
https://raw.githubusercontent.com/ag-ui-protocol/ag-ui/HEAD/integrations/langgraph/python/ag_ui_langgraph/utils.py
Create docstrings for API functions
# src/utils/converters.py from typing import List, Dict, Any, Optional, Tuple, Union import json import base64 import binascii import logging from ag_ui.core import ( Message, UserMessage, AssistantMessage, SystemMessage, ToolMessage, ToolCall, FunctionCall, TextInputContent, BinaryInputContent, InputContent...
--- +++ @@ -1,5 +1,6 @@ # src/utils/converters.py +"""Conversion utilities between AG-UI and ADK formats.""" from typing import List, Dict, Any, Optional, Tuple, Union import json @@ -17,12 +18,14 @@ logger = logging.getLogger(__name__) def _get_text_value(item: Union[dict, TextInputContent]) -> Optional[str]:...
https://raw.githubusercontent.com/ag-ui-protocol/ag-ui/HEAD/integrations/adk-middleware/python/src/ag_ui_adk/utils/converters.py
Generate helpful docstrings for debugging
# src/event_translator.py import dataclasses from collections.abc import Iterable, Mapping from typing import AsyncGenerator, Optional, Dict, Any, List import uuid from google.genai import types from ag_ui.core import ( BaseEvent, EventType, TextMessageStartEvent, TextMessageContentEvent, TextMessageEndEven...
--- +++ @@ -1,5 +1,6 @@ # src/event_translator.py +"""Event translator for converting ADK events to AG-UI protocol events.""" import dataclasses from collections.abc import Iterable, Mapping @@ -32,6 +33,11 @@ _HAS_THOUGHT_SUPPORT = False def _check_thought_support() -> bool: + """Check if the google-genai ...
https://raw.githubusercontent.com/ag-ui-protocol/ag-ui/HEAD/integrations/adk-middleware/python/src/ag_ui_adk/event_translator.py
Generate docstrings for each module
# /// script # requires-python = ">=3.12" # dependencies = [ # "uvicorn == 0.34.3", # "pydantic-ai==0.4.10" # ] # /// from __future__ import annotations from enum import StrEnum from textwrap import dedent from pydantic import BaseModel, Field from ag_ui.core import EventType, StateSnapshotEvent from pydantic_a...
--- +++ @@ -22,6 +22,7 @@ class SkillLevel(StrEnum): + """The level of skill required for the recipe.""" BEGINNER = 'Beginner' INTERMEDIATE = 'Intermediate' @@ -29,6 +30,7 @@ class SpecialPreferences(StrEnum): + """Special preferences for the recipe.""" HIGH_PROTEIN = 'High Protein' ...
https://raw.githubusercontent.com/ag-ui-protocol/ag-ui/HEAD/sdks/community/rust/crates/ag-ui-client/scripts/shared_state.py
Add docstrings to incomplete code
from ag_ui.core.events import BaseEvent AGUI_MEDIA_TYPE = "application/vnd.ag-ui.event+proto" class EventEncoder: def __init__(self, accept: str = None): pass def get_content_type(self) -> str: return "text/event-stream" def encode(self, event: BaseEvent) -> str: return self._en...
--- +++ @@ -1,17 +1,32 @@+""" +This module contains the EventEncoder class +""" from ag_ui.core.events import BaseEvent AGUI_MEDIA_TYPE = "application/vnd.ag-ui.event+proto" class EventEncoder: + """ + Encodes Agent User Interaction events. + """ def __init__(self, accept: str = None): p...
https://raw.githubusercontent.com/ag-ui-protocol/ag-ui/HEAD/sdks/python/ag_ui/encoder/encoder.py
Create documentation for each function signature
from __future__ import annotations import ast import os import json import uuid import logging import traceback from contextvars import ContextVar from typing import Any, Dict, List from json_repair import repair_json # AG‑UI Python SDK (events) from ag_ui.core.events import ( RunFinishedEvent, RunStartedEve...
--- +++ @@ -1,3 +1,18 @@+""" +AG-UI span processor for pyagentspec.tracing + +This module bridges pyagentspec.tracing spans/events to AG-UI events +(`ag_ui.core.events`). It mirrors the behavior of the exporter used in the +telemetry package but adapts to the event shapes defined under +`pyagentspec.tracing.events`. + ...
https://raw.githubusercontent.com/ag-ui-protocol/ag-ui/HEAD/integrations/agent-spec/python/ag_ui_agentspec/agentspec_tracing_exporter.py
Add well-formatted docstrings
from fastapi import FastAPI, Request from fastapi.responses import StreamingResponse from fastapi.middleware.cors import CORSMiddleware from ag_ui.core import RunAgentInput from ag_ui.encoder import EventEncoder from .agent import LangroidAgent def add_langroid_fastapi_endpoint( app: FastAPI, agent: Langroid...
--- +++ @@ -1,3 +1,4 @@+"""FastAPI endpoint utilities for Langroid integration.""" from fastapi import FastAPI, Request from fastapi.responses import StreamingResponse @@ -13,9 +14,11 @@ path: str, **kwargs ) -> None: + """Add a Langroid agent endpoint to FastAPI app.""" @app.post(path) ...
https://raw.githubusercontent.com/ag-ui-protocol/ag-ui/HEAD/integrations/langroid/python/src/ag_ui_langroid/endpoint.py
Create docstrings for reusable components
import json import logging import uuid from typing import Any, AsyncIterator, Dict, List from strands import Agent as StrandsAgentCore logger = logging.getLogger(__name__) from ag_ui.core import ( AssistantMessage, CustomEvent, EventType, MessagesSnapshotEvent, RunAgentInput, RunErrorEvent, ...
--- +++ @@ -1,3 +1,7 @@+"""AWS Strands Agent implementation for AG-UI. + +Simple adapter following the Agno pattern. +""" import json import logging @@ -39,6 +43,7 @@ class StrandsAgent: + """AWS Strands Agent wrapper for AG-UI integration.""" def __init__( self, @@ -71,6 +76,7 @@ sel...
https://raw.githubusercontent.com/ag-ui-protocol/ag-ui/HEAD/integrations/aws-strands/python/src/ag_ui_strands/agent.py
Add docstrings to clarify complex logic
import json import logging from typing import AsyncIterator, Any, Optional from ag_ui.core import ( EventType, BaseEvent, ToolCallStartEvent, ToolCallArgsEvent, ToolCallEndEvent, ToolCallResultEvent, StateSnapshotEvent, CustomEvent, ) from .utils import strip_mcp_prefix, _is_state_man...
--- +++ @@ -1,3 +1,9 @@+""" +import uuid +Event handlers for Claude SDK stream processing. + +Breaks down stream processing into focused handler functions. +""" import json import logging @@ -26,6 +32,22 @@ run_id: str, current_state: Optional[Any], ) -> tuple[Optional[Any], AsyncIterator[BaseEvent]]: + ...
https://raw.githubusercontent.com/ag-ui-protocol/ag-ui/HEAD/integrations/claude-agent-sdk/python/ag_ui_claude_sdk/handlers.py
Expand my code with proper documentation strings
import asyncio import logging from contextlib import suppress from typing import Any, AsyncIterator, Optional logger = logging.getLogger(__name__) _SHUTDOWN = object() class WorkerError: def __init__(self, exception: Exception): self.exception = exception class SessionWorker: def __init__(self, ...
--- +++ @@ -1,3 +1,9 @@+"""Session worker for Claude Agent SDK. + +Owns one ClaudeSDKClient per thread in a long-lived background task. +Uses queue-based communication to avoid receive_response() issues +on multi-turn conversations. +""" import asyncio import logging @@ -10,11 +16,18 @@ class WorkerError: + ...
https://raw.githubusercontent.com/ag-ui-protocol/ag-ui/HEAD/integrations/claude-agent-sdk/python/ag_ui_claude_sdk/session.py
Add docstrings for utility scripts
from typing import List, Optional, Union from google.adk.tools.base_tool import BaseTool from google.adk.tools.base_toolset import BaseToolset, ToolPredicate from google.adk.agents.readonly_context import ReadonlyContext class AGUIToolset(BaseToolset): def __init__( self, *, tool_filter: ...
--- +++ @@ -5,6 +5,10 @@ from google.adk.agents.readonly_context import ReadonlyContext class AGUIToolset(BaseToolset): + """ + Placeholder for AG-UI tool integration. + This will be replaced by ClientProxyToolset in actual usage. + """ def __init__( self, @@ -12,6 +16,12 @@ tool_...
https://raw.githubusercontent.com/ag-ui-protocol/ag-ui/HEAD/integrations/adk-middleware/python/src/ag_ui_adk/agui_toolset.py
Document classes and their methods
# src/adk_agent.py from ag_ui_adk.agui_toolset import AGUIToolset from typing import Optional, Dict, Callable, Any, AsyncGenerator, List, Iterable, TYPE_CHECKING, Tuple, Union if TYPE_CHECKING: from google.adk.apps import App import time import json import asyncio import inspect from datetime import datetime fr...
--- +++ @@ -1,5 +1,6 @@ # src/adk_agent.py +"""Main ADKAgent implementation for bridging AG-UI Protocol with Google ADK.""" from ag_ui_adk.agui_toolset import AGUIToolset from typing import Optional, Dict, Callable, Any, AsyncGenerator, List, Iterable, TYPE_CHECKING, Tuple, Union @@ -57,6 +58,11 @@ logger = loggi...
https://raw.githubusercontent.com/ag-ui-protocol/ag-ui/HEAD/integrations/adk-middleware/python/src/ag_ui_adk/adk_agent.py
Write Python docstrings for this snippet
# src/endpoint.py import json import logging import warnings from typing import Any, Callable, Coroutine, List, Optional from ag_ui.core import RunAgentInput from ag_ui.encoder import EventEncoder from fastapi import APIRouter, FastAPI, Request from fastapi.responses import JSONResponse, StreamingResponse from pydan...
--- +++ @@ -1,5 +1,6 @@ # src/endpoint.py +"""FastAPI endpoint for ADK middleware.""" import json import logging @@ -19,6 +20,10 @@ class AgentStateRequest(BaseModel): + """Request body for /agents/state endpoint. + + EXPERIMENTAL: This endpoint is subject to change in future versions. + """ thr...
https://raw.githubusercontent.com/ag-ui-protocol/ag-ui/HEAD/integrations/adk-middleware/python/src/ag_ui_adk/endpoint.py
Document all endpoints with docstrings
# src/ag_ui_adk/execution_state.py import asyncio import time from typing import Optional, Set import logging logger = logging.getLogger(__name__) class ExecutionState: def __init__( self, task: asyncio.Task, thread_id: str, event_queue: asyncio.Queue ): self.task =...
--- +++ @@ -1,5 +1,6 @@ # src/ag_ui_adk/execution_state.py +"""Execution state management for background ADK runs with tool support.""" import asyncio import time @@ -10,6 +11,13 @@ class ExecutionState: + """Manages the state of a background ADK execution. + + This class tracks: + - The background a...
https://raw.githubusercontent.com/ag-ui-protocol/ag-ui/HEAD/integrations/adk-middleware/python/src/ag_ui_adk/execution_state.py
Create Google-style docstrings for my code
from crewai.utilities.events.base_events import BaseEvent from ag_ui.core.events import ( ToolCallChunkEvent, TextMessageChunkEvent, CustomEvent, StateSnapshotEvent ) class BridgedToolCallChunkEvent(BaseEvent, ToolCallChunkEvent): class BridgedTextMessageChunkEvent(BaseEvent, TextMessageChunkEvent): class B...
--- +++ @@ -1,3 +1,6 @@+""" +This file is used to bridge the events from the crewai event bus to the ag-ui event bus. +""" from crewai.utilities.events.base_events import BaseEvent from ag_ui.core.events import ( @@ -8,9 +11,13 @@ ) class BridgedToolCallChunkEvent(BaseEvent, ToolCallChunkEvent): + """Bridged ...
https://raw.githubusercontent.com/ag-ui-protocol/ag-ui/HEAD/integrations/crew-ai/python/ag_ui_crewai/events.py
Auto-generate documentation strings for this file
from __future__ import annotations import inspect from dataclasses import dataclass, field from typing import ( Any, AsyncIterator, Awaitable, Callable, Dict, Iterable, List, Optional, ) from ag_ui.core import RunAgentInput StatePayload = Dict[str, Any] @dataclass class ToolCallCo...
--- +++ @@ -1,3 +1,4 @@+"""Configuration primitives for customizing Strands agent behavior.""" from __future__ import annotations @@ -22,6 +23,7 @@ @dataclass class ToolCallContext: + """Context passed to tool call hooks.""" input_data: RunAgentInput tool_name: str @@ -32,6 +34,7 @@ @dataclass ...
https://raw.githubusercontent.com/ag-ui-protocol/ag-ui/HEAD/integrations/aws-strands/python/src/ag_ui_strands/config.py
Create docstrings for reusable components
# src/config.py from __future__ import annotations from dataclasses import dataclass from typing import Any, Dict, Iterable, List, Optional @dataclass class PredictStateMapping: state_key: str tool: str tool_argument: str emit_confirm_tool: bool = True stream_tool_call: bool = False def t...
--- +++ @@ -1,5 +1,6 @@ # src/config.py +"""Configuration primitives for customizing ADK agent behavior.""" from __future__ import annotations @@ -9,6 +10,20 @@ @dataclass class PredictStateMapping: + """Declarative mapping telling the UI how to predict state from tool args. + + This enables predictive ...
https://raw.githubusercontent.com/ag-ui-protocol/ag-ui/HEAD/integrations/adk-middleware/python/src/ag_ui_adk/config.py
Write docstrings describing each step
# /// script # requires-python = ">=3.12" # dependencies = [ # "uvicorn == 0.34.3", # "pydantic-ai==0.4.10" # ] # /// from __future__ import annotations from textwrap import dedent from typing import Any, Literal from pydantic import BaseModel, Field from ag_ui.core import EventType, StateDeltaEvent, StateSnaps...
--- +++ @@ -24,6 +24,7 @@ class Step(BaseModel): + """Represents a step in a plan.""" description: str = Field(description='The description of the step') status: StepStatus = Field( @@ -33,11 +34,13 @@ class Plan(BaseModel): + """Represents a plan with multiple steps.""" steps: list[Ste...
https://raw.githubusercontent.com/ag-ui-protocol/ag-ui/HEAD/sdks/community/rust/crates/ag-ui-client/scripts/generative_ui.py
Write docstrings for backend logic
from fastapi import FastAPI from .agent import StrandsAgent from .endpoint import add_strands_fastapi_endpoint, add_ping def create_strands_app( agent: StrandsAgent, path: str = "/", ping_path: str | None = "/ping" ) -> FastAPI: app = FastAPI(title=f"AWS Strands - {agent.name}") # Add CORS ...
--- +++ @@ -1,3 +1,4 @@+"""Utility functions for AWS Strands integration.""" from fastapi import FastAPI from .agent import StrandsAgent @@ -8,6 +9,13 @@ path: str = "/", ping_path: str | None = "/ping" ) -> FastAPI: + """Create a FastAPI app with a single Strands agent endpoint and optional ping endp...
https://raw.githubusercontent.com/ag-ui-protocol/ag-ui/HEAD/integrations/aws-strands/python/src/ag_ui_strands/utils.py
Write docstrings including parameters and return values
from __future__ import annotations import logging from typing import Any, Set from ag_ui.core import Tool as AgUiTool from strands.tools.registry import ToolRegistry from strands.tools.tools import PythonAgentTool from strands.types.tools import ToolResult, ToolSpec, ToolUse logger = logging.getLogger(__name__) # ...
--- +++ @@ -1,3 +1,4 @@+"""Utilities for forwarding client-defined tools to the Strands agent at runtime.""" from __future__ import annotations @@ -16,6 +17,19 @@ def create_proxy_tool(ag_ui_tool: AgUiTool) -> PythonAgentTool: + """Convert an AG-UI ``Tool`` into a Strands ``PythonAgentTool``. + + The res...
https://raw.githubusercontent.com/ag-ui-protocol/ag-ui/HEAD/integrations/aws-strands/python/src/ag_ui_strands/client_proxy_tool.py
Add docstrings explaining edge cases
from typing import Any, Dict, Optional, Callable, AsyncIterator, Awaitable from typing_extensions import TypedDict from dataclasses import dataclass, field from ag_ui.core import RunAgentInput StatePayload = Dict[str, Any] @dataclass class ToolCallContext: input_data: RunAgentInput tool_name: str ...
--- +++ @@ -1,3 +1,4 @@+"""Type definitions for Langroid AG-UI integration.""" from typing import Any, Dict, Optional, Callable, AsyncIterator, Awaitable from typing_extensions import TypedDict @@ -11,6 +12,7 @@ @dataclass class ToolCallContext: + """Context passed to tool call hooks.""" input_data...
https://raw.githubusercontent.com/ag-ui-protocol/ag-ui/HEAD/integrations/langroid/python/src/ag_ui_langroid/types.py
Add docstrings to existing functions
# src/session_manager.py from typing import Dict, Optional, Set, Any, Union, Iterable, Tuple import asyncio import logging import time logger = logging.getLogger(__name__) # Keys used to store AG-UI metadata in session state for recovery after restart THREAD_ID_STATE_KEY = "_ag_ui_thread_id" APP_NAME_STATE_KEY = "_...
--- +++ @@ -1,5 +1,6 @@ # src/session_manager.py +"""Session manager that adds production features to ADK's native session service.""" from typing import Dict, Optional, Set, Any, Union, Iterable, Tuple import asyncio @@ -17,11 +18,22 @@ class SessionManager: + """Session manager that wraps ADK's session s...
https://raw.githubusercontent.com/ag-ui-protocol/ag-ui/HEAD/integrations/adk-middleware/python/src/ag_ui_adk/session_manager.py
Document functions with detailed explanations
import uuid from typing import List, Any, Optional, Mapping, Dict, Literal, TypedDict from litellm.types.utils import ( ModelResponse, Choices, Message as LiteLLMMessage, ChatCompletionMessageToolCall, Function as LiteLLMFunction ) from litellm.litellm_core_utils.streaming_handler import CustomStreamWrapper ...
--- +++ @@ -1,3 +1,6 @@+""" +This is a placeholder for the copilotkit_stream function. +""" import uuid from typing import List, Any, Optional, Mapping, Dict, Literal, TypedDict @@ -23,19 +26,54 @@ from .utils import yield_control class CopilotKitProperties(BaseModel): + """CopilotKit properties""" actio...
https://raw.githubusercontent.com/ag-ui-protocol/ag-ui/HEAD/integrations/crew-ai/python/ag_ui_crewai/sdk.py
Replace inline comments with docstrings
import json import logging import uuid from typing import Any, AsyncIterator, Dict, List, Optional logger = logging.getLogger(__name__) from ag_ui.core import ( EventType, RunAgentInput, RunErrorEvent, RunFinishedEvent, RunStartedEvent, StateSnapshotEvent, StateDeltaEvent, TextMessage...
--- +++ @@ -1,3 +1,7 @@+"""Langroid Agent implementation for AG-UI. + +Simple adapter that bridges Langroid ChatAgent/Task with the AG-UI protocol. +""" import json import logging @@ -33,6 +37,10 @@ class LangroidAgent: + """Langroid Agent wrapper for AG-UI integration. + + Wraps a Langroid ChatAgent ...
https://raw.githubusercontent.com/ag-ui-protocol/ag-ui/HEAD/integrations/langroid/python/src/ag_ui_langroid/agent.py
Document all public functions with docstrings
import json import logging from typing import Any, Dict, List, Optional, Tuple from ag_ui.core import RunAgentInput, AssistantMessage, ToolCall, FunctionCall, ToolMessage from .config import STATE_MANAGEMENT_TOOL_NAME, STATE_MANAGEMENT_TOOL_FULL_NAME logger = logging.getLogger(__name__) def fix_surrogates(s: str) ...
--- +++ @@ -1,3 +1,8 @@+""" +Utility functions for Claude Agent SDK adapter. + +Helper functions for message processing, tool conversion, and prompt building. +""" import json import logging @@ -10,6 +15,17 @@ def fix_surrogates(s: str) -> str: + """Re-assemble lone UTF-16 surrogate pairs into proper Unicode...
https://raw.githubusercontent.com/ag-ui-protocol/ag-ui/HEAD/integrations/claude-agent-sdk/python/ag_ui_claude_sdk/utils.py
Turn comments into proper docstrings
import logging import re import uuid import json from typing import Optional, List, Any, Union, AsyncGenerator, Generator, Literal, Dict import inspect from langgraph.graph.state import CompiledStateGraph try: from langchain.schema import BaseMessage, SystemMessage, ToolMessage except ImportError: # Langchain...
--- +++ @@ -612,6 +612,8 @@ ) def _filter_orphan_tool_messages(self, messages: list) -> list: + """Remove fake ToolMessages injected by patch_orphan_tool_calls, + but only between the last user message and the end of the list.""" # Find the index of the last HumanMessage last_...
https://raw.githubusercontent.com/ag-ui-protocol/ag-ui/HEAD/integrations/langgraph/python/ag_ui_langgraph/agent.py
Improve documentation using docstrings
# src/ag_ui_adk/client_proxy_toolset.py import asyncio from typing import Iterable, List, Optional, Union import logging from google.adk.tools import BaseTool from google.adk.tools.base_toolset import BaseToolset, ToolPredicate from google.adk.agents.readonly_context import ReadonlyContext from ag_ui.core import Too...
--- +++ @@ -1,5 +1,6 @@ # src/ag_ui_adk/client_proxy_toolset.py +"""Dynamic toolset creation for client-side tools.""" import asyncio from typing import Iterable, List, Optional, Union @@ -17,6 +18,11 @@ class ClientProxyToolset(BaseToolset): + """Dynamic toolset that creates proxy tools from AG-UI tool de...
https://raw.githubusercontent.com/ag-ui-protocol/ag-ui/HEAD/integrations/adk-middleware/python/src/ag_ui_adk/client_proxy_toolset.py
Add docstrings that explain inputs and outputs
import asyncio import os import logging import json import uuid from datetime import datetime from typing import AsyncIterator, Optional, List, Dict, Any, Union, TYPE_CHECKING from ag_ui.core import ( EventType, RunAgentInput, BaseEvent, AssistantMessage as AguiAssistantMessage, ToolCall as AguiTo...
--- +++ @@ -1,3 +1,4 @@+"""Claude Agent SDK adapter for AG-UI protocol.""" import asyncio import os @@ -71,6 +72,12 @@ class ClaudeAgentAdapter: + """ + AG-UI adapter for the Anthropic Claude Agent SDK. + + Manages the SDK client lifecycle internally via per-thread session workers. + Call ``run(...
https://raw.githubusercontent.com/ag-ui-protocol/ag-ui/HEAD/integrations/claude-agent-sdk/python/ag_ui_claude_sdk/adapter.py
Annotate my code with docstrings
import datetime import os import platform import re import subprocess import sys class File(object): def __init__(self, stream): self.content = stream.content self.__stream = stream self.__temp_name = "driver" @property def filename(self): try: filename = re.fi...
--- +++ @@ -1,641 +1,648 @@-import datetime -import os -import platform -import re -import subprocess -import sys - - -class File(object): - def __init__(self, stream): - self.content = stream.content - self.__stream = stream - self.__temp_name = "driver" - - @property - def filename(self)...
https://raw.githubusercontent.com/seleniumbase/SeleniumBase/HEAD/seleniumbase/core/detect_b_ver.py
Add docstrings for better understanding
import re _sub_regexes = { "tag": r"([a-zA-Z][-a-zA-Z0-9]{0,40}|\*)", "attribute": r"[.a-zA-Z_:][-\w:.]*(\(\))?)", "value": r"\s*[\w/:][-/\w\s,:;.\S]*", } _validation_re = ( r"(?P<node>" r"(" r"^id\([\"\']?(?P<idvalue>%(value)s)[\"\']?\)" r"|" r"(?P<nav>//?)(?P<tag>%(tag)s)" r"(\[(...
--- +++ @@ -1,3 +1,4 @@+"""Convert XPath selectors into CSS selectors""" import re _sub_regexes = { @@ -54,6 +55,12 @@ def _filter_xpath_grouping(xpath, original): + """ + This method removes the outer parentheses for xpath grouping. + The xpath converter will break otherwise. + Example: + "(//bu...
https://raw.githubusercontent.com/seleniumbase/SeleniumBase/HEAD/seleniumbase/fixtures/xpath_to_css.py
Generate docstrings with examples
already_uploaded_files = [] class S3LoggingBucket(object): from seleniumbase.config import settings def __init__( self, log_bucket=settings.S3_LOG_BUCKET, bucket_url=settings.S3_BUCKET_URL, selenium_access_key=settings.S3_SELENIUM_ACCESS_KEY, selenium_secret_key=setti...
--- +++ @@ -1,8 +1,11 @@+"""Methods for uploading/managing files on Amazon S3.""" already_uploaded_files = [] class S3LoggingBucket(object): + """A class for uploading log files from tests to Amazon S3. + Those files can then be shared easily.""" from seleniumbase.config import settings def __...
https://raw.githubusercontent.com/seleniumbase/SeleniumBase/HEAD/seleniumbase/core/s3_manager.py
Add docstrings for utility scripts
import asyncio import fasteners import mycdp import os import random import re import sys import time from contextlib import suppress from filelock import FileLock from seleniumbase import config as sb_config from seleniumbase.config import settings from seleniumbase.fixtures import constants from seleniumbase.fixtures...
--- +++ @@ -1,3 +1,4 @@+"""Add CDP methods to extend the driver""" import asyncio import fasteners import mycdp @@ -164,18 +165,29 @@ return self.loop def get_rd_host(self): + """Returns the remote-debugging host (likely 127.0.0.1)""" driver = self.driver if hasattr(driver, "c...
https://raw.githubusercontent.com/seleniumbase/SeleniumBase/HEAD/seleniumbase/core/sb_cdp.py
Add missing documentation to my Python functions
import os import re import warnings import zipfile from contextlib import suppress from seleniumbase.config import proxy_list from seleniumbase.config import settings from seleniumbase.fixtures import constants from seleniumbase.fixtures import page_utils from seleniumbase.fixtures import shared_utils DOWNLOADS_DIR = ...
--- +++ @@ -24,6 +24,12 @@ bypass_list=None, zip_it=True, ): + """Implementation of https://stackoverflow.com/a/35293284 for + https://stackoverflow.com/questions/12848327/ + (Run Selenium on a proxy server that requires authentication.) + Solution involves creating & adding a Chromium extension a...
https://raw.githubusercontent.com/seleniumbase/SeleniumBase/HEAD/seleniumbase/core/proxy_helper.py
Add docstrings to improve code quality
import colorama import logging import os import platform import requests import shutil import subprocess import sys import time import tarfile import urllib3 import zipfile from contextlib import suppress from seleniumbase.fixtures import constants from seleniumbase.fixtures import shared_utils from seleniumbase import...
--- +++ @@ -1,3 +1,33 @@+""" +Downloads the specified webdriver to "seleniumbase/drivers/" + +Usage: + sbase get {chromedriver|geckodriver|edgedriver| + iedriver|uc_driver|cft|chs} [OPTIONS] +Options: + VERSION Specify the version. + Tries to detect the needed version. + ...
https://raw.githubusercontent.com/seleniumbase/SeleniumBase/HEAD/seleniumbase/console_scripts/sb_install.py
Generate NumPy-style docstrings
class BlockedTest(Exception): pass class SkipTest(Exception): pass class DeprecatedTest(Exception): pass
--- +++ @@ -1,12 +1,23 @@+"""SeleniumBase MySQL-related exceptions. + +This feature is DEPRECATED! +Use self.skip() for skipping tests! + +Raising one of these in a test will cause the +test-state to be logged appropriately in the DB +for tests that use the SeleniumBase MySQL option.""" class BlockedTest(Exception...
https://raw.githubusercontent.com/seleniumbase/SeleniumBase/HEAD/seleniumbase/fixtures/errors.py
Auto-generate documentation strings for this file
import ast import sys import time from contextlib import suppress from nose.plugins import Plugin from seleniumbase import config as sb_config from seleniumbase.config import settings from seleniumbase.core import download_helper from seleniumbase.core import log_helper from seleniumbase.core import report_helper from ...
--- +++ @@ -1,3 +1,4 @@+"""Base Plugin for SeleniumBase tests that run with pynose / nosetests""" import ast import sys import time @@ -17,6 +18,24 @@ class Base(Plugin): + """This plugin adds the following command-line options to pynose: + --env=ENV (Set the test env. Access with "self.env" in tests.) + ...
https://raw.githubusercontent.com/seleniumbase/SeleniumBase/HEAD/seleniumbase/plugins/base_plugin.py
Add docstrings to incomplete code
import re import requests import time from contextlib import suppress from selenium.common.exceptions import NoSuchElementException from selenium.common.exceptions import WebDriverException from selenium.webdriver.common.by import By from seleniumbase import config as sb_config from seleniumbase.config import settings ...
--- +++ @@ -1,3 +1,4 @@+"""This module contains useful Javascript utility methods for BaseCase.""" import re import requests import time @@ -20,6 +21,14 @@ def wait_for_ready_state_complete(driver, timeout=settings.LARGE_TIMEOUT): + """The DOM (Document Object Model) has a property called "readyState". + W...
https://raw.githubusercontent.com/seleniumbase/SeleniumBase/HEAD/seleniumbase/fixtures/js_utils.py
Add docstrings for internal functions
import fasteners import os import re import requests from selenium.webdriver.common.by import By from seleniumbase.fixtures import constants from seleniumbase.fixtures import css_to_xpath def get_domain_url(url): if not url.startswith(("http://", "https://")): return url url_header = url.split("://")[...
--- +++ @@ -1,3 +1,4 @@+"""This module contains useful utility methods""" import fasteners import os import re @@ -8,6 +9,12 @@ def get_domain_url(url): + """ + Use this to convert a url like this: + https://blog.xkcd.com/2014/07/22/what-if-book-tour/ + Into this: + https://blog.xkcd.com + """ ...
https://raw.githubusercontent.com/seleniumbase/SeleniumBase/HEAD/seleniumbase/fixtures/page_utils.py
Add docstrings for production code
import colorama import os import subprocess import sys import tkinter as tk from seleniumbase.fixtures import shared_utils from tkinter import messagebox from tkinter.scrolledtext import ScrolledText def set_colors(use_colors): c0 = "" c1 = "" c2 = "" c3 = "" c4 = "" c5 = "" cr = "" if...
--- +++ @@ -1,3 +1,20 @@+""" +Launches the SeleniumBase Case Plans Generator. + +Usage: + seleniumbase caseplans [OPTIONAL PATH or TEST FILE] + sbase caseplans [OPTIONAL PATH or TEST FILE] + +Examples: + sbase caseplans + sbase caseplans -k agent + sbase caseplans -m marker2 + sbase...
https://raw.githubusercontent.com/seleniumbase/SeleniumBase/HEAD/seleniumbase/console_scripts/sb_caseplans.py
Add docstrings for production code
from contextlib import suppress from selenium.webdriver.remote.webdriver import WebDriver from selenium.webdriver.remote.webelement import WebElement from seleniumbase.config import settings from seleniumbase.fixtures import js_utils from seleniumbase.fixtures import page_actions from seleniumbase.fixtures import page_...
--- +++ @@ -1,3 +1,4 @@+"""Add new methods to extend the driver""" from contextlib import suppress from selenium.webdriver.remote.webdriver import WebDriver from selenium.webdriver.remote.webelement import WebElement @@ -17,6 +18,7 @@ self.command_executor = driver.command_executor def __is_cdp_sw...
https://raw.githubusercontent.com/seleniumbase/SeleniumBase/HEAD/seleniumbase/core/sb_driver.py
Improve my code by adding docstrings
class LinkTextNotFoundException(Exception): pass class NoSuchFileException(Exception): pass class NoSuchOptionException(Exception): pass class NotConnectedException(Exception): pass class NotUsingChromeException(Exception): pass class NotUsingChromiumException(Exception): pass clas...
--- +++ @@ -1,3 +1,17 @@+""" SeleniumBase Exceptions + LinkTextNotFoundException => Called when expected link text is not visible. + NoSuchFileException => Called when self.assert_downloaded_file(...) fails. + NoSuchOptionException => Called when select_option_by_*() lacks the option. + NotConnectedExceptio...
https://raw.githubusercontent.com/seleniumbase/SeleniumBase/HEAD/seleniumbase/common/exceptions.py
Add standardized docstrings across the file
import colorama import os import pathlib import platform import sys import time from contextlib import suppress from seleniumbase import config as sb_config from seleniumbase.config import settings from seleniumbase.fixtures import constants def pip_install(package, version=None): import fasteners import subp...
--- +++ @@ -1,3 +1,4 @@+"""Shared utility methods""" import colorama import os import pathlib @@ -49,6 +50,14 @@ def get_mfa_code(totp_key=None): + """Returns a time-based one-time password based on the + Google Authenticator algorithm for multi-factor authentication. + If the "totp_key" is not specifie...
https://raw.githubusercontent.com/seleniumbase/SeleniumBase/HEAD/seleniumbase/fixtures/shared_utils.py
Write clean docstrings for readability
import os import re import textwrap import time from seleniumbase import config as sb_config from seleniumbase.config import settings from seleniumbase.core import style_sheet from seleniumbase.fixtures import constants from seleniumbase.fixtures import js_utils from seleniumbase.fixtures import page_actions EXPORTED_...
--- +++ @@ -1,3 +1,5 @@+"""This module contains methods for running website tours. +These helper methods SHOULD NOT be called directly from tests.""" import os import re import textwrap @@ -13,6 +15,9 @@ def activate_bootstrap(driver): + """Allows you to use Bootstrap Tours with SeleniumBase + http://boots...
https://raw.githubusercontent.com/seleniumbase/SeleniumBase/HEAD/seleniumbase/core/tour_helper.py
Add docstrings for better understanding
import os import shutil import sys import time from selenium.common.exceptions import NoAlertPresentException from selenium.common.exceptions import WebDriverException from seleniumbase import BaseCase from seleniumbase.core.style_sheet import get_report_style from seleniumbase.config import settings from seleniumbase....
--- +++ @@ -1,3 +1,4 @@+"""Manually verify pages quickly while assisted by automation.""" import os import shutil import sys @@ -54,6 +55,10 @@ self.__manual_page_check(*args) def auto_close_results(self): + """If this method is called, the results page will automatically close + at the ...
https://raw.githubusercontent.com/seleniumbase/SeleniumBase/HEAD/seleniumbase/masterqa/master_qa.py
Include argument descriptions in docstrings
class DatabaseManager: def __init__(self, database_env="test", conf_creds=None): import fasteners import time from seleniumbase import config as sb_config from seleniumbase.config import settings from seleniumbase.core import settings_parser from seleniumbase.fixtu...
--- +++ @@ -1,8 +1,11 @@+"""Wrapper for MySQL DB functions""" class DatabaseManager: + """This class wraps MySQL database methods for easy use.""" def __init__(self, database_env="test", conf_creds=None): + """Create a connection to the MySQL DB.""" import fasteners import time ...
https://raw.githubusercontent.com/seleniumbase/SeleniumBase/HEAD/seleniumbase/core/mysql.py
Add verbose docstrings with examples
import time class ApplicationManager: @classmethod def generate_application_string(cls, test): app_env = "test" if hasattr(test, "env"): app_env = test.env elif hasattr(test, "environment"): app_env = test.environment start_time = int(time.time() * 10...
--- +++ @@ -2,9 +2,12 @@ class ApplicationManager: + """Generating application strings for the Testcase Database.""" @classmethod def generate_application_string(cls, test): + """Generate a string based on some of the given information + that's pulled from the test object: app_env, star...
https://raw.githubusercontent.com/seleniumbase/SeleniumBase/HEAD/seleniumbase/core/application_manager.py
Write documentation strings for class attributes
import ast import colorama import os import re import sys from contextlib import suppress from seleniumbase import config as sb_config from seleniumbase.config import settings from seleniumbase.core import detect_b_ver from seleniumbase.core import download_helper from seleniumbase.core import log_helper from seleniumb...
--- +++ @@ -1,3 +1,110 @@+""" +The SeleniumBase-Behave Connector configures command-line options. +****************************************************************** +Examples: +behave -D browser=edge -D dashboard -D headless +behave -D rs -D dashboard +behave -D agent="User Agent String" -D demo +*********************...
https://raw.githubusercontent.com/seleniumbase/SeleniumBase/HEAD/seleniumbase/behave/behave_sb.py
Write clean docstrings for readability
import os import sys from seleniumbase.core import sb_driver class DriverContext(): def __init__(self, *args, **kwargs): self.driver = Driver(*args, **kwargs) def __enter__(self): return self.driver def __exit__(self, exc_type, exc_val, exc_tb): try: if ( ...
--- +++ @@ -1,3 +1,41 @@+""" +The SeleniumBase Driver as a Python Context Manager or a returnable object. +########################################################################### + +The SeleniumBase Driver as a context manager: +Usage --> ``with DriverContext() as driver:`` + +Example --> + +```python +from seleniu...
https://raw.githubusercontent.com/seleniumbase/SeleniumBase/HEAD/seleniumbase/plugins/driver_manager.py
Add inline docstrings for readability
import os import time from contextlib import suppress from filelock import FileLock from selenium.common.exceptions import ElementNotInteractableException from selenium.common.exceptions import ElementNotVisibleException from selenium.common.exceptions import NoAlertPresentException from selenium.common.exceptions impo...
--- +++ @@ -1,3 +1,22 @@+"""This module contains useful methods for waiting on elements to load. + +These methods improve and expand on existing WebDriver commands. +Improvements include making WebDriver commands more robust and more reliable +by giving page elements enough time to load before taking action on them. + ...
https://raw.githubusercontent.com/seleniumbase/SeleniumBase/HEAD/seleniumbase/fixtures/page_actions.py
Write documentation strings for class attributes
import colorama import logging import math import sys import time import warnings from contextlib import contextmanager from functools import wraps from seleniumbase.common.exceptions import TimeoutException c1 = colorama.Fore.BLUE + colorama.Back.LIGHTYELLOW_EX cr = colorama.Style.RESET_ALL if "linux" in sys.platform...
--- +++ @@ -16,6 +16,23 @@ @contextmanager def print_runtime(description=None, limit=None): + """Print the runtime duration of a method or "with"-block after completion. + If limit, fail if the runtime duration exceeds the limit after completion. + + Method / Function example usage -> + from selenium...
https://raw.githubusercontent.com/seleniumbase/SeleniumBase/HEAD/seleniumbase/common/decorators.py
Add well-formatted docstrings
import time import uuid from nose.plugins import Plugin from seleniumbase.fixtures import constants class DBReporting(Plugin): name = "db_reporting" # Usage: --with-db_reporting def __init__(self): Plugin.__init__(self) self.execution_guid = str(uuid.uuid4()) self.testcase_guid = Non...
--- +++ @@ -1,3 +1,4 @@+"""DB Reporting Plugin for SeleniumBase tests that use pynose / nosetests""" import time import uuid from nose.plugins import Plugin @@ -5,6 +6,7 @@ class DBReporting(Plugin): + """This plugin records test results in the Testcase Database.""" name = "db_reporting" # Usage: --with...
https://raw.githubusercontent.com/seleniumbase/SeleniumBase/HEAD/seleniumbase/plugins/db_reporting_plugin.py
Help me comply with documentation standards
import colorama import os import subprocess import sys import tkinter as tk from seleniumbase import config as sb_config from seleniumbase.fixtures import page_utils from seleniumbase.fixtures import shared_utils from tkinter import messagebox sb_config.rec_subprocess_p = None sb_config.rec_subprocess_used = False sys...
--- +++ @@ -1,3 +1,20 @@+""" +** recorder ** + +Launches the SeleniumBase Recorder Desktop App. + +Usage: + seleniumbase recorder [OPTIONS] + sbase recorder [OPTIONS] + +Options: + --uc / --undetected (Use undetectable mode.) + --cdp (Same as "--uc" and "--undetectable".) + --behave (Also outpu...
https://raw.githubusercontent.com/seleniumbase/SeleniumBase/HEAD/seleniumbase/console_scripts/sb_recorder.py
Generate docstrings for this script
import os import shutil import sys import time from contextlib import suppress from seleniumbase import config as sb_config from seleniumbase.config import settings from seleniumbase.fixtures import constants from seleniumbase.fixtures import shared_utils python3_11_or_newer = False if sys.version_info >= (3, 11): ...
--- +++ @@ -15,6 +15,7 @@ def __is_cdp_swap_needed(driver): + """If the driver is disconnected, use a CDP method when available.""" return shared_utils.is_cdp_swap_needed(driver) @@ -51,6 +52,7 @@ def get_master_time(): + """Returns (timestamp, the_date, the_time)""" import datetime t...
https://raw.githubusercontent.com/seleniumbase/SeleniumBase/HEAD/seleniumbase/core/log_helper.py
Document functions with detailed explanations
from cssselect.xpath import GenericTranslator class ConvertibleToCssTranslator(GenericTranslator): def css_to_xpath(self, css, prefix="//"): return super().css_to_xpath(css, prefix) def xpath_attrib_equals(self, xpath, name, value): xpath.add_condition("%s=%s" % (name, self.xpath_literal(val...
--- +++ @@ -1,7 +1,12 @@+"""Convert CSS selectors into XPath selectors""" from cssselect.xpath import GenericTranslator class ConvertibleToCssTranslator(GenericTranslator): + """An implementation of :py:class:`cssselect.GenericTranslator` with + XPath output that more readily converts back to CSS selectors....
https://raw.githubusercontent.com/seleniumbase/SeleniumBase/HEAD/seleniumbase/fixtures/css_to_xpath.py
Generate docstrings with parameter types
import os from nose.plugins import Plugin from seleniumbase.config import settings from seleniumbase.core import log_helper class PageSource(Plugin): name = "page_source" # Usage: --with-page_source logfile_name = settings.PAGE_SOURCE_NAME def options(self, parser, env): super().options(parser, ...
--- +++ @@ -1,3 +1,4 @@+"""PageSource Plugin for SeleniumBase tests that run with pynose / nosetests""" import os from nose.plugins import Plugin from seleniumbase.config import settings @@ -5,6 +6,7 @@ class PageSource(Plugin): + """Capture the page source after a test fails.""" name = "page_source" # ...
https://raw.githubusercontent.com/seleniumbase/SeleniumBase/HEAD/seleniumbase/plugins/page_source.py
Generate docstrings for exported functions
import os from nose.plugins import Plugin from seleniumbase.config import settings class ScreenShots(Plugin): name = "screen_shots" logfile_name = settings.SCREENSHOT_NAME def options(self, parser, env): super().options(parser, env=env) def configure(self, options, conf): super().con...
--- +++ @@ -1,9 +1,11 @@+"""Screenshot Plugin for SeleniumBase tests that run with pynose / nosetests""" import os from nose.plugins import Plugin from seleniumbase.config import settings class ScreenShots(Plugin): + """This plugin takes a screenshot when a test fails.""" name = "screen_shots" logf...
https://raw.githubusercontent.com/seleniumbase/SeleniumBase/HEAD/seleniumbase/plugins/screen_shots.py
Help me comply with documentation standards
import uuid import os from nose.plugins import Plugin class S3Logging(Plugin): name = "s3_logging" # Usage: --with-s3-logging def configure(self, options, conf): super().configure(options, conf) self.options = options self.test_id = None def save_data_to_logs(self, data, file_na...
--- +++ @@ -1,12 +1,15 @@+"""S3 Logging Plugin for SeleniumBase tests that run with pynose / nosetests""" import uuid import os from nose.plugins import Plugin class S3Logging(Plugin): + """The plugin for uploading test logs to the S3 bucket specified.""" name = "s3_logging" # Usage: --with-s3-logging ...
https://raw.githubusercontent.com/seleniumbase/SeleniumBase/HEAD/seleniumbase/plugins/s3_logging_plugin.py
Generate docstrings for exported functions
import os import sys from contextlib import suppress from nose.plugins import Plugin from seleniumbase import config as sb_config from seleniumbase.config import settings from seleniumbase.core import detect_b_ver from seleniumbase.core import proxy_helper from seleniumbase.fixtures import constants from seleniumbase.f...
--- +++ @@ -1,3 +1,4 @@+"""Selenium Plugin for SeleniumBase tests that run with pynose / nosetests""" import os import sys from contextlib import suppress @@ -11,6 +12,98 @@ class SeleniumBrowser(Plugin): + """This plugin adds the following command-line options to pynose: + --browser=BROWSER (The web brow...
https://raw.githubusercontent.com/seleniumbase/SeleniumBase/HEAD/seleniumbase/plugins/selenium_plugin.py
Add docstrings to make code maintainable
import logging import os import pathlib import secrets import sys import tempfile import zipfile from contextlib import suppress from seleniumbase.config import settings from seleniumbase.drivers import chromium_drivers from seleniumbase.fixtures import constants from seleniumbase.fixtures import shared_utils from typi...
--- +++ @@ -1,395 +1,441 @@-import logging -import os -import pathlib -import secrets -import sys -import tempfile -import zipfile -from contextlib import suppress -from seleniumbase.config import settings -from seleniumbase.drivers import chromium_drivers -from seleniumbase.fixtures import constants -from seleniumbase...
https://raw.githubusercontent.com/seleniumbase/SeleniumBase/HEAD/seleniumbase/undetected/cdp_driver/config.py
Add docstrings with type hints explained
from contextlib import contextmanager, suppress from typing import Any, Generator from seleniumbase import BaseCase @contextmanager # Usage: -> ``with SB() as sb:`` def SB( test=None, # Test Mode: Output, Logging, Continue on failure unless "rtf". rtf=None, # Shortcut / Duplicate of "raise_test_failure". ...
--- +++ @@ -1,3 +1,28 @@+""" +SeleniumBase as a Python Context Manager. +######################################### + +The SeleniumBase SB Context Manager: +Usage --> ``with SB() as sb:`` + +Example --> + +```python +from seleniumbase import SB + +with SB(uc=True, test=True) as sb: + url = "https://google.com/ncr" + ...
https://raw.githubusercontent.com/seleniumbase/SeleniumBase/HEAD/seleniumbase/plugins/sb_manager.py
Document my Python code with docstrings
from __future__ import annotations import asyncio import fasteners import logging import os import sys import time import types import typing from contextlib import suppress from seleniumbase import config as sb_config from seleniumbase import extensions from seleniumbase.config import settings from seleniumbase.core i...
--- +++ @@ -1,880 +1,969 @@-from __future__ import annotations -import asyncio -import fasteners -import logging -import os -import sys -import time -import types -import typing -from contextlib import suppress -from seleniumbase import config as sb_config -from seleniumbase import extensions -from seleniumbase.config ...
https://raw.githubusercontent.com/seleniumbase/SeleniumBase/HEAD/seleniumbase/undetected/cdp_driver/cdp_util.py
Provide docstrings following PEP 257
from __future__ import annotations import asyncio import atexit import fasteners import http.cookiejar import json import logging import os import pathlib import pickle import re import shutil import time import urllib.parse import urllib.request import warnings from collections import defaultdict from contextlib impor...
--- +++ @@ -1,1056 +1,1179 @@-from __future__ import annotations -import asyncio -import atexit -import fasteners -import http.cookiejar -import json -import logging -import os -import pathlib -import pickle -import re -import shutil -import time -import urllib.parse -import urllib.request -import warnings -from collec...
https://raw.githubusercontent.com/seleniumbase/SeleniumBase/HEAD/seleniumbase/undetected/cdp_driver/browser.py
Add docstrings with type hints explained
from __future__ import annotations import asyncio import collections import inspect import itertools import json import logging import sys import types import warnings from typing import ( Optional, Generator, Union, Awaitable, Callable, Any, TypeVar, ) import websockets from websockets.prot...
--- +++ @@ -1,580 +1,651 @@-from __future__ import annotations -import asyncio -import collections -import inspect -import itertools -import json -import logging -import sys -import types -import warnings -from typing import ( - Optional, - Generator, - Union, - Awaitable, - Callable, - Any, - Type...
https://raw.githubusercontent.com/seleniumbase/SeleniumBase/HEAD/seleniumbase/undetected/cdp_driver/connection.py
Add inline docstrings for readability
import io import logging import os import random import re import string import sys import time import zipfile from contextlib import suppress from seleniumbase.console_scripts import sb_install from seleniumbase.fixtures import shared_utils logger = logging.getLogger(__name__) IS_POSIX = sys.platform.startswith(("dar...
--- +++ @@ -1,302 +1,316 @@-import io -import logging -import os -import random -import re -import string -import sys -import time -import zipfile -from contextlib import suppress -from seleniumbase.console_scripts import sb_install -from seleniumbase.fixtures import shared_utils - -logger = logging.getLogger(__name__)...
https://raw.githubusercontent.com/seleniumbase/SeleniumBase/HEAD/seleniumbase/undetected/patcher.py
Add structured docstrings to improve clarity
import os import shutil import sys from urllib.request import urlopen SELENIUM_JAR = ( "http://selenium-release.storage.googleapis.com" "/3.141/selenium-server-standalone-3.141.59.jar" ) JAR_FILE = "selenium-server-standalone-3.141.59.jar" RENAMED_JAR_FILE = "selenium-server-standalone.jar" dir_path = os.path...
--- +++ @@ -1,3 +1,4 @@+"""Downloads the Selenium Server JAR file and renames it.""" import os import shutil import sys @@ -16,6 +17,7 @@ def download_selenium_server(): + """Downloads the Selenium Server JAR file.""" try: local_file = open(JAR_FILE, mode="wb") remote_file = urlopen(SEL...
https://raw.githubusercontent.com/seleniumbase/SeleniumBase/HEAD/seleniumbase/utilities/selenium_grid/download_selenium_server.py
Add missing documentation to my Python functions
import logging import os import re import requests import subprocess import sys import time from filelock import FileLock import selenium.webdriver.chrome.service import selenium.webdriver.chrome.webdriver import selenium.webdriver.common.service import selenium.webdriver.remote.command from contextlib import suppress ...
--- +++ @@ -1,627 +1,695 @@-import logging -import os -import re -import requests -import subprocess -import sys -import time -from filelock import FileLock -import selenium.webdriver.chrome.service -import selenium.webdriver.chrome.webdriver -import selenium.webdriver.common.service -import selenium.webdriver.remote.c...
https://raw.githubusercontent.com/seleniumbase/SeleniumBase/HEAD/seleniumbase/undetected/__init__.py
Add well-formatted docstrings
from __future__ import annotations import asyncio import base64 import datetime import logging import pathlib import re import sys import urllib.parse import warnings from contextlib import suppress from filelock import FileLock from seleniumbase import config as sb_config from seleniumbase.fixtures import constants fr...
--- +++ @@ -1,1498 +1,1896 @@-from __future__ import annotations -import asyncio -import base64 -import datetime -import logging -import pathlib -import re -import sys -import urllib.parse -import warnings -from contextlib import suppress -from filelock import FileLock -from seleniumbase import config as sb_config -fro...
https://raw.githubusercontent.com/seleniumbase/SeleniumBase/HEAD/seleniumbase/undetected/cdp_driver/tab.py
Add documentation for all methods
from __future__ import annotations import asyncio import logging import pathlib import secrets import typing from contextlib import suppress from . import cdp_util as util from ._contradict import ContraDict from .config import PathLike import mycdp as cdp import mycdp.input_ import mycdp.dom import mycdp.overlay impor...
--- +++ @@ -1,1082 +1,1240 @@-from __future__ import annotations -import asyncio -import logging -import pathlib -import secrets -import typing -from contextlib import suppress -from . import cdp_util as util -from ._contradict import ContraDict -from .config import PathLike -import mycdp as cdp -import mycdp.input_ -i...
https://raw.githubusercontent.com/seleniumbase/SeleniumBase/HEAD/seleniumbase/undetected/cdp_driver/element.py
Add standardized docstrings across the file
import warnings as _warnings from collections.abc import Mapping as _Mapping, Sequence as _Sequence import logging __logger__ = logging.getLogger(__name__) __all__ = ["cdict", "ContraDict"] def cdict(*args, **kwargs): return ContraDict(*args, **kwargs) class ContraDict(dict): __module__ = None def __i...
--- +++ @@ -1,90 +1,110 @@-import warnings as _warnings -from collections.abc import Mapping as _Mapping, Sequence as _Sequence -import logging - -__logger__ = logging.getLogger(__name__) -__all__ = ["cdict", "ContraDict"] - - -def cdict(*args, **kwargs): - return ContraDict(*args, **kwargs) - - -class ContraDict(di...
https://raw.githubusercontent.com/seleniumbase/SeleniumBase/HEAD/seleniumbase/undetected/cdp_driver/_contradict.py
Create Google-style docstrings for my code
import json import os from contextlib import suppress from selenium.webdriver.chromium.options import ChromiumOptions class ChromeOptions(ChromiumOptions): _session = None _user_data_dir = None @property def user_data_dir(self): return self._user_data_dir @user_data_dir.setter def us...
--- +++ @@ -1,75 +1,78 @@-import json -import os -from contextlib import suppress -from selenium.webdriver.chromium.options import ChromiumOptions - - -class ChromeOptions(ChromiumOptions): - _session = None - _user_data_dir = None - - @property - def user_data_dir(self): - return self._user_data_dir...
https://raw.githubusercontent.com/seleniumbase/SeleniumBase/HEAD/seleniumbase/undetected/options.py
Write proper docstrings for these functions
import asyncio from collections.abc import Mapping from collections.abc import Sequence from functools import wraps import logging import threading import time import traceback from typing import Any from typing import Awaitable from typing import Callable from typing import List from typing import Optional class Str...
--- +++ @@ -14,10 +14,22 @@ class Structure(dict): + """ + This is a dict-like object structure, which you should subclass + Only properties defined in the class context are used on initialization. + + See example + """ _store = {} def __init__(self, *a, **kw): + """ + Ins...
https://raw.githubusercontent.com/ultrafunkamsterdam/undetected-chromedriver/HEAD/undetected_chromedriver/devtool.py
Add docstrings that explain inputs and outputs
#!/usr/bin/env python3 # this module is part of undetected_chromedriver from packaging.version import Version as LooseVersion import io import json import logging import os import pathlib import platform import random import re import shutil import string import subprocess import sys import time from urllib.request im...
--- +++ @@ -49,6 +49,15 @@ version_main: int = 0, user_multi_procs=False, ): + """ + Args: + executable_path: None = automatic + a full file path to the chromedriver executable + force: False + terminate processes w...
https://raw.githubusercontent.com/ultrafunkamsterdam/undetected-chromedriver/HEAD/undetected_chromedriver/patcher.py
Add detailed docstrings explaining each function
#!/usr/bin/env python3 from __future__ import annotations __version__ = "3.5.5" import json import logging import os import pathlib import re import shutil import subprocess import sys import tempfile import time from weakref import finalize import selenium.webdriver.chrome.service import selenium.webdriver.chrome...
--- +++ @@ -1,5 +1,19 @@ #!/usr/bin/env python3 +""" + + 888 888 d8b + 888 888 Y8P + 888 888 + .d8888b 88888b. 888d888 .d88b. 888...
https://raw.githubusercontent.com/ultrafunkamsterdam/undetected-chromedriver/HEAD/undetected_chromedriver/__init__.py
Generate NumPy-style docstrings
from dataclasses import dataclass, field from memori.memory.augmentation._message import ConversationMessage @dataclass class EntityData: id: str | None = None @dataclass class ProcessData: id: str | None = None @dataclass class AttributionData: entity: EntityData = field(default_factory=EntityDa...
--- +++ @@ -1,3 +1,12 @@+r""" + __ __ _ +| \/ | ___ _ __ ___ ___ _ __(_) +| |\/| |/ _ \ '_ ` _ \ / _ \| '__| | +| | | | __/ | | | | | (_) | | | | +|_| |_|\___|_| |_| |_|\___/|_| |_| + perfectam memoriam + memorilabs.ai +""" from dataclasses ...
https://raw.githubusercontent.com/MemoriLabs/Memori/HEAD/memori/memory/augmentation/augmentations/memori/models.py
Write docstrings describing functionality
import hashlib from dataclasses import dataclass, field def hash_id(value: str | None) -> str | None: if not value: return None return hashlib.sha256(value.encode()).hexdigest() @dataclass class ConversationData: messages: list summary: str | None = None @dataclass class SdkVersionData: ...
--- +++ @@ -1,3 +1,12 @@+r""" + __ __ _ +| \/ | ___ _ __ ___ ___ _ __(_) +| |\/| |/ _ \ '_ ` _ \ / _ \| '__| | +| | | | __/ | | | | | (_) | | | | +|_| |_|\___|_| |_| |_|\___/|_| |_| + perfectam memoriam + memorilabs.ai +""" import hashlib fro...
https://raw.githubusercontent.com/MemoriLabs/Memori/HEAD/memori/memory/augmentation/_models.py