instruction stringclasses 100
values | code stringlengths 78 193k | response stringlengths 259 170k | file stringlengths 59 203 |
|---|---|---|---|
Write docstrings describing each step | # Originally from https://github.com/ELS-RD/transformer-deploy.
# Apache License, Version 2.0, Copyright (c) 2022 Lefebvre Dalloz Services
from typing import Callable, Dict, List, OrderedDict, Tuple
import tensorrt as trt
import torch
from tensorrt import ICudaEngine, IExecutionContext
from tensorrt.tensorrt import (... | --- +++ @@ -26,6 +26,14 @@
def fix_fp16_network(network_definition: INetworkDefinition) -> INetworkDefinition:
+ """
+ Mixed precision on TensorRT can generate scores very far from Pytorch because of some operator being saturated.
+ Indeed, FP16 can't store very large and very small numbers like FP32.
+ ... | https://raw.githubusercontent.com/jina-ai/clip-as-service/HEAD/server/clip_server/model/trt_utils.py |
Add docstrings to existing functions |
import warnings
import torch
import numpy as np
from torch import nn
from dataclasses import dataclass
from typing import Tuple, Union, Optional
from copy import deepcopy
from clip_server.helper import __cast_dtype__
from open_clip.transformer import QuickGELU, LayerNorm, LayerNormFp32, Attention
from open_clip.timm_m... | --- +++ @@ -1,3 +1,12 @@+""" CLIP Model
+
+Adapted from https://github.com/mlfoundations/open_clip.
+
+Originally MIT License, Copyright (c) 2012-2021 Gabriel Ilharco, Mitchell Wortsman,
+Nicholas Carlini, Rohan Taori, Achal Dave, Vaishaal Shankar,
+John Miller, Hongseok Namkoong, Hannaneh Hajishirzi, Ali Farhadi,
+Lud... | https://raw.githubusercontent.com/jina-ai/clip-as-service/HEAD/server/clip_server/model/model.py |
Write docstrings for utility functions | # Originally from https://github.com/openai/CLIP. MIT License, Copyright (c) 2021 OpenAI
import gzip
import html
import os
import regex as re
from functools import lru_cache
import ftfy
from clip_server.helper import __resources_path__
@lru_cache()
def default_bpe():
return os.path.join(__resources_path__, 'bp... | --- +++ @@ -18,6 +18,15 @@
@lru_cache()
def bytes_to_unicode():
+ """
+ Returns list of utf-8 byte and a corresponding list of unicode strings.
+ The reversible bpe codes work on unicode strings.
+ This means you need a large # of unicode characters in your vocab if you want to avoid UNKs.
+ When you'... | https://raw.githubusercontent.com/jina-ai/clip-as-service/HEAD/server/clip_server/model/simple_tokenizer.py |
Write reusable docstrings | from copy import deepcopy
import numpy as np
from gymnasium import spaces
from stable_baselines3.common.preprocessing import is_image_space, is_image_space_channels_first
from stable_baselines3.common.vec_env.base_vec_env import VecEnv, VecEnvStepReturn, VecEnvWrapper
class VecTransposeImage(VecEnvWrapper):
de... | --- +++ @@ -8,6 +8,14 @@
class VecTransposeImage(VecEnvWrapper):
+ """
+ Re-order channels, from HxWxC to CxHxW.
+ It is required for PyTorch convolution layers.
+
+ :param venv:
+ :param skip: Skip this wrapper if needed as we rely on heuristic to apply it or not,
+ which may result in unwant... | https://raw.githubusercontent.com/DLR-RM/stable-baselines3/HEAD/stable_baselines3/common/vec_env/vec_transpose.py |
Add docstrings that explain purpose and usage | from __future__ import print_function
import os
import sys
import time
import torch
import math
import numpy as np
import cv2
def _gaussian(
size=3, sigma=0.25, amplitude=1, normalize=False, width=None,
height=None, sigma_horz=None, sigma_vert=None, mean_horz=0.5,
mean_vert=0.5):
# handle ... | --- +++ @@ -54,6 +54,22 @@
def transform(point, center, scale, resolution, invert=False):
+ """Generate and affine transformation matrix.
+
+ Given a set of points, a center, a scale and a targer resolution, the
+ function generates and affine transformation matrix. If invert is ``True``
+ it will produ... | https://raw.githubusercontent.com/Rudrabha/Wav2Lip/HEAD/face_detection/utils.py |
Generate missing documentation strings | import os
import sys
import time
import random
import httplib2
from pathlib import Path
from logstream import log
from oauth2client.file import Storage
from apiclient.discovery import build
from apiclient.errors import HttpError
from apiclient.http import MediaFileUpload
from oauth2client.tools import argparser, run_f... | --- +++ @@ -65,6 +65,12 @@
def get_authenticated_service():
+ """
+ This method retrieves the YouTube service.
+
+ Returns:
+ any: The authenticated YouTube service.
+ """
flow = flow_from_clientsecrets(
CLIENT_SECRETS_FILE, scope=SCOPES, message=MISSING_CLIENT_SECRETS_MESSAGE
... | https://raw.githubusercontent.com/FujiwaraChoki/MoneyPrinter/HEAD/Backend/youtube.py |
Generate docstrings for exported functions | import json
import queue
import re
import time
class LogStream:
def __init__(self, maxsize: int = 500):
self._queue: queue.Queue = queue.Queue(maxsize=maxsize)
def clear(self) -> None:
while True:
try:
self._queue.get_nowait()
except queue.Empty:
... | --- +++ @@ -5,11 +5,13 @@
class LogStream:
+ """Thread-safe log queue that doubles as an SSE generator."""
def __init__(self, maxsize: int = 500):
self._queue: queue.Queue = queue.Queue(maxsize=maxsize)
def clear(self) -> None:
+ """Drain all pending items from the queue."""
... | https://raw.githubusercontent.com/FujiwaraChoki/MoneyPrinter/HEAD/Backend/logstream.py |
Document all endpoints with docstrings | import copy
import warnings
from typing import Any
import numpy as np
import torch as th
from gymnasium import spaces
from stable_baselines3.common.buffers import DictReplayBuffer
from stable_baselines3.common.type_aliases import DictReplayBufferSamples
from stable_baselines3.common.vec_env import VecEnv, VecNormaliz... | --- +++ @@ -13,6 +13,37 @@
class HerReplayBuffer(DictReplayBuffer):
+ """
+ Hindsight Experience Replay (HER) buffer.
+ Paper: https://arxiv.org/abs/1707.01495
+
+ Replay buffer for sampling HER (Hindsight Experience Replay) transitions.
+
+ .. note::
+
+ Compared to other implementations, the `... | https://raw.githubusercontent.com/DLR-RM/stable-baselines3/HEAD/stable_baselines3/her/her_replay_buffer.py |
Document all public functions with docstrings | import os
import sys
import random
import logging
import shutil
from pathlib import Path
from typing import Optional
from termcolor import colored
BASE_DIR = Path(__file__).resolve().parent
PROJECT_ROOT = BASE_DIR.parent
TEMP_DIR = PROJECT_ROOT / "temp"
SUBTITLES_DIR = PROJECT_ROOT / "subtitles"
SONGS_DIR = PROJECT_... | --- +++ @@ -23,6 +23,15 @@
def clean_dir(path: str) -> None:
+ """
+ Removes every file in a directory.
+
+ Args:
+ path (str): Path to directory.
+
+ Returns:
+ None
+ """
try:
directory = Path(path).expanduser().resolve()
directory.mkdir(parents=True, exist_ok=T... | https://raw.githubusercontent.com/FujiwaraChoki/MoneyPrinter/HEAD/Backend/utils.py |
Fill in missing docstrings in my code | import re
import os
import json
from ollama import Client, ResponseError
from dotenv import load_dotenv
from logstream import log
from typing import Tuple, List, Optional
from utils import ENV_FILE
# Load environment variables
load_dotenv(ENV_FILE)
# Set environment variables
OLLAMA_BASE_URL = os.getenv("OLLAMA_BASE... | --- +++ @@ -32,6 +32,12 @@
def list_ollama_models() -> Tuple[List[str], str]:
+ """
+ Returns available Ollama model names and configured default model.
+
+ Returns:
+ Tuple[List[str], str]: (available model names, default model)
+ """
try:
response = _ollama_client().list()
ex... | https://raw.githubusercontent.com/FujiwaraChoki/MoneyPrinter/HEAD/Backend/gpt.py |
Add detailed docstrings explaining each function | import os
import uuid
import requests
import srt_equalizer
import assemblyai as aai
from typing import List
from pathlib import Path
from moviepy import (
AudioFileClip,
CompositeVideoClip,
TextClip,
VideoFileClip,
concatenate_videoclips,
)
from dotenv import load_dotenv
from logstream import log
... | --- +++ @@ -26,6 +26,16 @@
def save_video(video_url: str, directory: str = str(TEMP_DIR)) -> str:
+ """
+ Saves a video from a given URL and returns the path to the video.
+
+ Args:
+ video_url (str): The URL of the video to save.
+ directory (str): The path of the temporary directory to save... | https://raw.githubusercontent.com/FujiwaraChoki/MoneyPrinter/HEAD/Backend/video.py |
Add docstrings for internal functions |
from typing import List, Dict, Any, Optional, Literal
from datetime import datetime
from uuid import UUID
from pydantic import BaseModel, Field, ConfigDict, field_validator
from enum import Enum
# Enums
class SearchType(str, Enum):
SEMANTIC = "semantic"
KEYWORD = "keyword"
HYBRID = "hybrid"
class Message... | --- +++ @@ -1,3 +1,6 @@+"""
+Pydantic models for data validation and serialization.
+"""
from typing import List, Dict, Any, Optional, Literal
from datetime import datetime
@@ -7,17 +10,20 @@
# Enums
class SearchType(str, Enum):
+ """Search type enum."""
SEMANTIC = "semantic"
KEYWORD = "keyword"
... | https://raw.githubusercontent.com/coleam00/context-engineering-intro/HEAD/use-cases/agent-factory-with-subagents/agents/rag_agent/utils/models.py |
Add docstrings that explain logic |
import os
import json
import asyncio
from typing import List, Dict, Any, Optional, Tuple
from datetime import datetime, timedelta, timezone
from contextlib import asynccontextmanager
from uuid import UUID
import logging
import asyncpg
from asyncpg.pool import Pool
from dotenv import load_dotenv
# Load environment va... | --- +++ @@ -1,3 +1,6 @@+"""
+Database utilities for PostgreSQL connection and operations.
+"""
import os
import json
@@ -19,8 +22,15 @@
class DatabasePool:
+ """Manages PostgreSQL connection pool."""
def __init__(self, database_url: Optional[str] = None):
+ """
+ Initialize database ... | https://raw.githubusercontent.com/coleam00/context-engineering-intro/HEAD/use-cases/agent-factory-with-subagents/agents/rag_agent/utils/db_utils.py |
Add docstrings to meet PEP guidelines | #!/usr/bin/env python3
import os
import sys
import shutil
import argparse
from pathlib import Path
from typing import List, Tuple
def get_template_files() -> List[Tuple[str, str]]:
template_root = Path(__file__).parent
files_to_copy = []
# Core template files
core_files = [
"CLAUDE.md",
... | --- +++ @@ -1,4 +1,17 @@ #!/usr/bin/env python3
+"""
+PydanticAI Template Copy Script
+
+Copies the complete PydanticAI context engineering template to a target directory
+for starting new PydanticAI agent development projects.
+
+Usage:
+ python copy_template.py <target_directory>
+
+Example:
+ python copy_templ... | https://raw.githubusercontent.com/coleam00/context-engineering-intro/HEAD/use-cases/pydantic-ai/copy_template.py |
Document all endpoints with docstrings |
import os
import asyncio
import logging
import json
import glob
from pathlib import Path
from typing import List, Dict, Any, Optional
from datetime import datetime
import argparse
import asyncpg
from dotenv import load_dotenv
from .chunker import ChunkingConfig, create_chunker, DocumentChunk
from .embedder import cr... | --- +++ @@ -1,3 +1,6 @@+"""
+Main ingestion script for processing markdown documents into vector DB and knowledge graph.
+"""
import os
import asyncio
@@ -34,6 +37,7 @@
class DocumentIngestionPipeline:
+ """Pipeline for ingesting documents into vector DB and knowledge graph."""
def __init__(
... | https://raw.githubusercontent.com/coleam00/context-engineering-intro/HEAD/use-cases/agent-factory-with-subagents/agents/rag_agent/ingestion/ingest.py |
Help me write clear docstrings |
from typing import Optional
from pydantic_ai.providers.openai import OpenAIProvider
from pydantic_ai.models.openai import OpenAIModel
from settings import load_settings
def get_llm_model(model_choice: Optional[str] = None) -> OpenAIModel:
settings = load_settings()
llm_choice = model_choice or settings.... | --- +++ @@ -1,3 +1,4 @@+"""Model providers for Semantic Search Agent."""
from typing import Optional
from pydantic_ai.providers.openai import OpenAIProvider
@@ -6,6 +7,16 @@
def get_llm_model(model_choice: Optional[str] = None) -> OpenAIModel:
+ """
+ Get LLM model configuration based on environment varia... | https://raw.githubusercontent.com/coleam00/context-engineering-intro/HEAD/use-cases/agent-factory-with-subagents/agents/rag_agent/providers.py |
Add docstrings to improve collaboration | #!/usr/bin/env python3
import os
import sys
import shutil
import argparse
from pathlib import Path
from typing import List, Tuple, Set
import fnmatch
def parse_gitignore(gitignore_path: Path) -> Set[str]:
ignore_patterns = set()
if not gitignore_path.exists():
return ignore_patterns
try... | --- +++ @@ -1,4 +1,18 @@ #!/usr/bin/env python3
+"""
+MCP Server Template Copy Script
+
+Copies the complete MCP server context engineering template to a target directory
+for starting new MCP server development projects. Uses gitignore-aware copying
+to avoid copying build artifacts and dependencies.
+
+Usage:
+ py... | https://raw.githubusercontent.com/coleam00/context-engineering-intro/HEAD/use-cases/mcp-server/copy_template.py |
Help me document legacy Python code |
import os
import asyncio
import logging
from typing import List, Dict, Any, Optional, Tuple
from datetime import datetime
import json
from openai import RateLimitError, APIError
from dotenv import load_dotenv
from .chunker import DocumentChunk
# Import flexible providers
try:
from ..utils.providers import get_e... | --- +++ @@ -1,3 +1,6 @@+"""
+Document embedding generation for vector search.
+"""
import os
import asyncio
@@ -32,6 +35,7 @@
class EmbeddingGenerator:
+ """Generates embeddings for document chunks."""
def __init__(
self,
@@ -40,6 +44,15 @@ max_retries: int = 3,
retry_del... | https://raw.githubusercontent.com/coleam00/context-engineering-intro/HEAD/use-cases/agent-factory-with-subagents/agents/rag_agent/ingestion/embedder.py |
Create docstrings for API functions |
from dataclasses import dataclass, field
from typing import Optional, Dict, Any
import asyncpg
import openai
from settings import load_settings
@dataclass
class AgentDependencies:
# Core dependencies
db_pool: Optional[asyncpg.Pool] = None
openai_client: Optional[openai.AsyncOpenAI] = None
settin... | --- +++ @@ -1,3 +1,4 @@+"""Dependencies for Semantic Search Agent."""
from dataclasses import dataclass, field
from typing import Optional, Dict, Any
@@ -8,6 +9,7 @@
@dataclass
class AgentDependencies:
+ """Dependencies injected into the agent context."""
# Core dependencies
db_pool: Optional[... | https://raw.githubusercontent.com/coleam00/context-engineering-intro/HEAD/use-cases/agent-factory-with-subagents/agents/rag_agent/dependencies.py |
Fully document this Python code with docstrings |
from pydantic_ai import RunContext
from typing import Optional
from dependencies import AgentDependencies
MAIN_SYSTEM_PROMPT = """You are a helpful assistant with access to a knowledge base that you can search when needed.
ALWAYS Start with Hybrid search
## Your Capabilities:
1. **Conversation**: Engage naturally ... | --- +++ @@ -1,3 +1,4 @@+"""System prompts for Semantic Search Agent."""
from pydantic_ai import RunContext
from typing import Optional
@@ -35,6 +36,7 @@
def get_dynamic_prompt(ctx: RunContext[AgentDependencies]) -> str:
+ """Generate dynamic prompt based on context."""
deps = ctx.deps
parts = []
... | https://raw.githubusercontent.com/coleam00/context-engineering-intro/HEAD/use-cases/agent-factory-with-subagents/agents/rag_agent/prompts.py |
Write docstrings for utility functions |
from typing import Optional, List, Dict, Any
from pydantic_ai import RunContext
from pydantic import BaseModel, Field
import asyncpg
import json
from dependencies import AgentDependencies
class SearchResult(BaseModel):
chunk_id: str
document_id: str
content: str
similarity: float
metadata: Dict[s... | --- +++ @@ -1,3 +1,4 @@+"""Search tools for Semantic Search Agent."""
from typing import Optional, List, Dict, Any
from pydantic_ai import RunContext
@@ -8,6 +9,7 @@
class SearchResult(BaseModel):
+ """Model for search results."""
chunk_id: str
document_id: str
content: str
@@ -22,6 +24,17 @@ ... | https://raw.githubusercontent.com/coleam00/context-engineering-intro/HEAD/use-cases/agent-factory-with-subagents/agents/rag_agent/tools.py |
Write docstrings that follow conventions | #!/usr/bin/env python3
import asyncio
import sys
import uuid
from typing import List
from rich.console import Console
from rich.panel import Panel
from rich.prompt import Prompt
from rich.markdown import Markdown
from pydantic_ai import Agent
from agent import search_agent
from dependencies import AgentDependencies
... | --- +++ @@ -1,4 +1,5 @@ #!/usr/bin/env python3
+"""Command-line interface for Semantic Search Agent."""
import asyncio
import sys
@@ -19,6 +20,7 @@
async def stream_agent_interaction(user_input: str, conversation_history: List[str], deps: AgentDependencies) -> tuple[str, str]:
+ """Stream agent interaction w... | https://raw.githubusercontent.com/coleam00/context-engineering-intro/HEAD/use-cases/agent-factory-with-subagents/agents/rag_agent/cli.py |
Add docstrings to improve readability |
import os
from typing import Optional
from pydantic_ai.models.openai import OpenAIModel
from pydantic_ai.providers.openai import OpenAIProvider
import openai
from dotenv import load_dotenv
# Load environment variables
load_dotenv()
def get_llm_model() -> OpenAIModel:
llm_choice = os.getenv('LLM_CHOICE', 'gpt-4.... | --- +++ @@ -1,3 +1,6 @@+"""
+Simplified provider configuration for OpenAI models only.
+"""
import os
from typing import Optional
@@ -11,6 +14,12 @@
def get_llm_model() -> OpenAIModel:
+ """
+ Get LLM model configuration for OpenAI.
+
+ Returns:
+ Configured OpenAI model
+ """
llm_ch... | https://raw.githubusercontent.com/coleam00/context-engineering-intro/HEAD/use-cases/agent-factory-with-subagents/agents/rag_agent/utils/providers.py |
Generate docstrings with examples |
import os
import re
import logging
from typing import List, Dict, Any, Optional, Tuple
from dataclasses import dataclass
import asyncio
from dotenv import load_dotenv
# Load environment variables
load_dotenv()
logger = logging.getLogger(__name__)
# Import flexible providers
try:
from ..utils.providers import g... | --- +++ @@ -1,3 +1,6 @@+"""
+Semantic chunking implementation for intelligent document splitting.
+"""
import os
import re
@@ -30,6 +33,7 @@
@dataclass
class ChunkingConfig:
+ """Configuration for chunking."""
chunk_size: int = 1000
chunk_overlap: int = 200
max_chunk_size: int = 2000
@@ -38,6 +... | https://raw.githubusercontent.com/coleam00/context-engineering-intro/HEAD/use-cases/agent-factory-with-subagents/agents/rag_agent/ingestion/chunker.py |
Add docstrings to clarify complex logic |
from pydantic_settings import BaseSettings
from pydantic import Field, ConfigDict
from dotenv import load_dotenv
from typing import Optional
# Load environment variables from .env file
load_dotenv()
class Settings(BaseSettings):
model_config = ConfigDict(
env_file=".env",
env_file_encoding=... | --- +++ @@ -1,3 +1,4 @@+"""Settings configuration for Semantic Search Agent."""
from pydantic_settings import BaseSettings
from pydantic import Field, ConfigDict
@@ -9,6 +10,7 @@
class Settings(BaseSettings):
+ """Application settings with environment variable support."""
model_config = ConfigDict... | https://raw.githubusercontent.com/coleam00/context-engineering-intro/HEAD/use-cases/agent-factory-with-subagents/agents/rag_agent/settings.py |
Create docstrings for reusable components | import requests
import math
import os.path
import re
import argparse
import tld
from core.colors import info
from core.config import VERBOSE, BAD_TYPES
from urllib.parse import urlparse
def regxy(pattern, response, supress_regex, custom):
try:
matches = re.findall(r'%s' % pattern, response)
for... | --- +++ @@ -13,6 +13,7 @@
def regxy(pattern, response, supress_regex, custom):
+ """Extract a string based on regex pattern supplied by user."""
try:
matches = re.findall(r'%s' % pattern, response)
for match in matches:
@@ -23,6 +24,19 @@
def is_link(url, processed, files):
+ """
+ ... | https://raw.githubusercontent.com/s0md3v/Photon/HEAD/core/utils.py |
Add clean documentation to messy code | from re import findall
from requests import get
def find_subdomains(domain):
result = set()
response = get('https://findsubdomains.com/subdomains-of/' + domain).text
matches = findall(r'(?s)<div class="domains js-domain-name">(.*?)</div>', response)
for match in matches:
result.add(match.repl... | --- +++ @@ -1,12 +1,14 @@+"""Support for findsubdomains.com."""
from re import findall
from requests import get
def find_subdomains(domain):
+ """Find subdomains according to the TLD."""
result = set()
response = get('https://findsubdomains.com/subdomains-of/' + domain).text
matches = findall... | https://raw.githubusercontent.com/s0md3v/Photon/HEAD/plugins/find_subdomains.py |
Generate missing documentation strings | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
from __future__ import print_function
import argparse
import os
import re
import requests
import sys
import time
import warnings
import random
from core.colors import good, info, run, green, red, white, end, bad
# Just a fancy ass banner
print('''%s ____ __ ... | --- +++ @@ -1,420 +1,425 @@-#!/usr/bin/env python3
-# -*- coding: utf-8 -*-
-from __future__ import print_function
-
-import argparse
-import os
-import re
-import requests
-import sys
-import time
-import warnings
-import random
-
-from core.colors import good, info, run, green, red, white, end, bad
-
-# Just a fancy ... | https://raw.githubusercontent.com/s0md3v/Photon/HEAD/photon.py |
Add docstrings that explain purpose and usage | import datetime
import hashlib
import json
import logging
import platform
import re
import shutil
import tarfile
import tempfile
import urllib.error
from functools import partial
from pathlib import Path
from typing import Any
from urllib.request import urlopen
from pipx import constants, paths
from pipx.animate impor... | --- +++ @@ -48,6 +48,10 @@
def download_python_build_standalone(python_version: str, override: bool = False):
+ """When all other python executable resolutions have failed,
+ attempt to download and use an appropriate python build
+ from https://github.com/astral-sh/python-build-standalone
+ and unpack ... | https://raw.githubusercontent.com/pypa/pipx/HEAD/src/pipx/standalone_python.py |
Add docstrings to improve collaboration | import datetime
import hashlib
import logging
import re
import sys
import time
import urllib.parse
import urllib.request
from pathlib import Path
from shutil import which
from typing import NoReturn, Optional, Union
from packaging.requirements import InvalidRequirement, Requirement
from pipx import paths
from pipx.co... | --- +++ @@ -44,6 +44,8 @@
def maybe_script_content(app: str, is_path: bool) -> Optional[Union[str, Path]]:
+ """If the app is a script, return its content.
+ Return None if it should be treated as a package name."""
# Look for a local file first.
app_path = Path(app)
@@ -209,6 +211,9 @@ verbos... | https://raw.githubusercontent.com/pypa/pipx/HEAD/src/pipx/commands/run.py |
Add detailed documentation for each class | import logging
import os
import sys
from collections.abc import Sequence
from pathlib import Path
from typing import Optional
from pipx import commands, paths
from pipx.colors import bold, red
from pipx.commands.common import expose_resources_globally
from pipx.constants import EXIT_CODE_OK, ExitCode
from pipx.emojis ... | --- +++ @@ -25,6 +25,7 @@ force: bool,
upgrading_all: bool,
) -> int:
+ """Returns 1 if package version changed, 0 if same version"""
package_metadata = venv.package_metadata[package_name]
if package_metadata.package_or_url is None:
@@ -117,6 +118,7 @@ python: Optional[str] = None,
pyt... | https://raw.githubusercontent.com/pypa/pipx/HEAD/src/pipx/commands/upgrade.py |
Add structured docstrings to improve clarity | import json
import sys
from collections.abc import Iterator
from pathlib import Path
from typing import Optional
from pipx import commands, paths
from pipx.commands.common import package_name_from_spec, run_post_install_actions
from pipx.constants import (
EXIT_CODE_INSTALL_VENV_EXISTS,
EXIT_CODE_OK,
ExitC... | --- +++ @@ -36,6 +36,7 @@ suffix: str = "",
python_flag_passed=False,
) -> ExitCode:
+ """Returns pipx exit code."""
# package_spec is anything pip-installable, including package_name, vcs spec,
# zip file, or tar.gz file.
@@ -127,6 +128,7 @@
def extract_venv_metadata(spec_metadata_file: ... | https://raw.githubusercontent.com/pypa/pipx/HEAD/src/pipx/commands/install.py |
Write docstrings for this repository | import logging
import os
import random
import re
import shutil
import string
import subprocess
import sys
import textwrap
from collections.abc import Sequence
from dataclasses import dataclass
from pathlib import Path
from re import Pattern
from typing import (
Any,
NoReturn,
Optional,
Union,
)
from pi... | --- +++ @@ -163,6 +163,7 @@ log_stderr: bool = True,
run_dir: Optional[str] = None,
) -> "subprocess.CompletedProcess[str]":
+ """Run arbitrary command as subprocess, capturing stderr and stout"""
env = dict(os.environ)
env = _fix_subprocess_env(env)
@@ -220,6 +221,29 @@
def analyze_pip_out... | https://raw.githubusercontent.com/pypa/pipx/HEAD/src/pipx/util.py |
Generate descriptive docstrings automatically | import logging
import site
import sys
from pathlib import Path
from typing import Optional
import userpath # type: ignore[import-not-found]
from pipx import paths
from pipx.constants import EXIT_CODE_OK, ExitCode
from pipx.emojis import hazard, stars
from pipx.util import pipx_wrap
logger = logging.getLogger(__name... | --- +++ @@ -15,6 +15,9 @@
def get_pipx_user_bin_path() -> Optional[Path]:
+ """Returns None if pipx is not installed using `pip --user`
+ Otherwise returns parent dir of pipx binary
+ """
# NOTE: using this method to detect pip user-installed pipx will return
# None if pipx was installed as edi... | https://raw.githubusercontent.com/pypa/pipx/HEAD/src/pipx/commands/ensure_path.py |
Document my Python code with docstrings | # Valid package specifiers for pipx:
# PEP508-compliant
# git+<URL>
# <URL>
# <pypi_package_name>
# <pypi_package_name><version_specifier>
# <local_path>
import logging
import re
import urllib.parse
from dataclasses import dataclass
from pathlib import Path
from typing import Optional
from packaging.requi... | --- +++ @@ -33,6 +33,7 @@
def _split_path_extras(package_spec: str) -> tuple[str, str]:
+ """Returns (path, extras_string)"""
package_spec_extras_re = re.search(r"(.+)(\[.+\])", package_spec)
if package_spec_extras_re:
return (package_spec_extras_re.group(1), package_spec_extras_re.group(2))
@... | https://raw.githubusercontent.com/pypa/pipx/HEAD/src/pipx/package_specifier.py |
Create docstrings for all classes and functions | import json
import logging
import re
import shutil
import time
from collections.abc import Generator
from pathlib import Path
from typing import TYPE_CHECKING, NoReturn, Optional
if TYPE_CHECKING:
from subprocess import CompletedProcess
try:
from importlib.metadata import Distribution, EntryPoint
except Impor... | --- +++ @@ -56,6 +56,7 @@
class VenvContainer:
+ """A collection of venvs managed by pipx."""
def __init__(self, root: Path):
self._root = root
@@ -67,6 +68,7 @@ return str(self._root)
def iter_venv_dirs(self) -> Generator[Path, None, None]:
+ """Iterate venv directories in ... | https://raw.githubusercontent.com/pypa/pipx/HEAD/src/pipx/venv.py |
Add return value explanations in docstrings | #!/usr/bin/env python3
import os
import sys
import json
# Add plugin root to Python path for imports
PLUGIN_ROOT = os.environ.get('CLAUDE_PLUGIN_ROOT')
if PLUGIN_ROOT and PLUGIN_ROOT not in sys.path:
sys.path.insert(0, PLUGIN_ROOT)
try:
from core.config_loader import load_rules
from core.rule_engine impo... | --- +++ @@ -1,4 +1,9 @@ #!/usr/bin/env python3
+"""UserPromptSubmit hook executor for hookify plugin.
+
+This script is called by Claude Code when user submits a prompt.
+It reads .claude/hookify.*.local.md files and evaluates rules.
+"""
import os
import sys
@@ -19,6 +24,7 @@
def main():
+ """Main entry poi... | https://raw.githubusercontent.com/anthropics/claude-plugins-official/HEAD/plugins/hookify/hooks/userpromptsubmit.py |
Add docstrings to improve readability | #!/usr/bin/env python3
import os
import sys
import glob
import re
from typing import List, Optional, Dict, Any
from dataclasses import dataclass, field
@dataclass
class Condition:
field: str # "command", "new_text", "old_text", "file_path", etc.
operator: str # "regex_match", "contains", "equals", etc.
... | --- +++ @@ -1,4 +1,8 @@ #!/usr/bin/env python3
+"""Configuration loader for hookify plugin.
+
+Loads and parses .claude/hookify.*.local.md files.
+"""
import os
import sys
@@ -10,12 +14,14 @@
@dataclass
class Condition:
+ """A single condition for matching."""
field: str # "command", "new_text", "old_te... | https://raw.githubusercontent.com/anthropics/claude-plugins-official/HEAD/plugins/hookify/core/config_loader.py |
Add clean documentation to messy code | #!/usr/bin/env python3
import argparse
import json
import random
import sys
import tempfile
import time
import webbrowser
from pathlib import Path
import anthropic
from scripts.generate_report import generate_html
from scripts.improve_description import improve_description
from scripts.run_eval import find_project_r... | --- +++ @@ -1,4 +1,10 @@ #!/usr/bin/env python3
+"""Run the eval + improve loop until all pass or max iterations reached.
+
+Combines run_eval.py and improve_description.py in a loop, tracking history
+and returning the best description found. Supports train/test split to prevent
+overfitting.
+"""
import argparse
... | https://raw.githubusercontent.com/anthropics/claude-plugins-official/HEAD/plugins/skill-creator/skills/skill-creator/scripts/run_loop.py |
Write clean docstrings for readability | #!/usr/bin/env python3
import os
import sys
import json
# Add plugin root to Python path for imports
PLUGIN_ROOT = os.environ.get('CLAUDE_PLUGIN_ROOT')
if PLUGIN_ROOT and PLUGIN_ROOT not in sys.path:
sys.path.insert(0, PLUGIN_ROOT)
try:
from core.config_loader import load_rules
from core.rule_engine impo... | --- +++ @@ -1,4 +1,9 @@ #!/usr/bin/env python3
+"""PostToolUse hook executor for hookify plugin.
+
+This script is called by Claude Code after a tool executes.
+It reads .claude/hookify.*.local.md files and evaluates rules.
+"""
import os
import sys
@@ -19,6 +24,7 @@
def main():
+ """Main entry point for Pos... | https://raw.githubusercontent.com/anthropics/claude-plugins-official/HEAD/plugins/hookify/hooks/posttooluse.py |
Write proper docstrings for these functions | #!/usr/bin/env python3
import re
import sys
from functools import lru_cache
from typing import List, Dict, Any, Optional
# Import from local module
from core.config_loader import Rule, Condition
# Cache compiled regexes (max 128 patterns)
@lru_cache(maxsize=128)
def compile_regex(pattern: str) -> re.Pattern:
re... | --- +++ @@ -1,4 +1,5 @@ #!/usr/bin/env python3
+"""Rule evaluation engine for hookify plugin."""
import re
import sys
@@ -12,16 +13,39 @@ # Cache compiled regexes (max 128 patterns)
@lru_cache(maxsize=128)
def compile_regex(pattern: str) -> re.Pattern:
+ """Compile regex pattern with caching.
+
+ Args:
+ ... | https://raw.githubusercontent.com/anthropics/claude-plugins-official/HEAD/plugins/hookify/core/rule_engine.py |
Help me document legacy Python code | #!/usr/bin/env python3
import argparse
import json
import re
import sys
from pathlib import Path
import anthropic
from scripts.utils import parse_skill_md
def improve_description(
client: anthropic.Anthropic,
skill_name: str,
skill_content: str,
current_description: str,
eval_results: dict,
... | --- +++ @@ -1,4 +1,9 @@ #!/usr/bin/env python3
+"""Improve a skill description based on eval results.
+
+Takes eval results (from run_eval.py) and generates an improved description
+using Claude with extended thinking.
+"""
import argparse
import json
@@ -23,6 +28,7 @@ log_dir: Path | None = None,
iteratio... | https://raw.githubusercontent.com/anthropics/claude-plugins-official/HEAD/plugins/skill-creator/skills/skill-creator/scripts/improve_description.py |
Generate docstrings for this script | #!/usr/bin/env python3
import os
import sys
import json
# Add plugin root to Python path for imports
PLUGIN_ROOT = os.environ.get('CLAUDE_PLUGIN_ROOT')
if PLUGIN_ROOT and PLUGIN_ROOT not in sys.path:
sys.path.insert(0, PLUGIN_ROOT)
try:
from core.config_loader import load_rules
from core.rule_engine impo... | --- +++ @@ -1,4 +1,9 @@ #!/usr/bin/env python3
+"""Stop hook executor for hookify plugin.
+
+This script is called by Claude Code when agent wants to stop.
+It reads .claude/hookify.*.local.md files and evaluates stop rules.
+"""
import os
import sys
@@ -19,6 +24,7 @@
def main():
+ """Main entry point for St... | https://raw.githubusercontent.com/anthropics/claude-plugins-official/HEAD/plugins/hookify/hooks/stop.py |
Auto-generate documentation strings for this file | #!/usr/bin/env python3
import json
import os
import random
import sys
from datetime import datetime
# Debug log file
DEBUG_LOG_FILE = "/tmp/security-warnings-log.txt"
def debug_log(message):
try:
timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S.%f")[:-3]
with open(DEBUG_LOG_FILE, "a") as f... | --- +++ @@ -1,4 +1,8 @@ #!/usr/bin/env python3
+"""
+Security Reminder Hook for Claude Code
+This hook checks for security patterns in file edits and warns about potential vulnerabilities.
+"""
import json
import os
@@ -11,6 +15,7 @@
def debug_log(message):
+ """Append debug message to log file with timestam... | https://raw.githubusercontent.com/anthropics/claude-plugins-official/HEAD/plugins/security-guidance/hooks/security_reminder_hook.py |
Write docstrings for utility functions | #!/usr/bin/env python3
import os
import sys
import json
# Add plugin root to Python path for imports
PLUGIN_ROOT = os.environ.get('CLAUDE_PLUGIN_ROOT')
if PLUGIN_ROOT and PLUGIN_ROOT not in sys.path:
sys.path.insert(0, PLUGIN_ROOT)
try:
from core.config_loader import load_rules
from core.rule_engine impo... | --- +++ @@ -1,4 +1,9 @@ #!/usr/bin/env python3
+"""PreToolUse hook executor for hookify plugin.
+
+This script is called by Claude Code before any tool executes.
+It reads .claude/hookify.*.local.md files and evaluates rules.
+"""
import os
import sys
@@ -20,6 +25,7 @@
def main():
+ """Main entry point for P... | https://raw.githubusercontent.com/anthropics/claude-plugins-official/HEAD/plugins/hookify/hooks/pretooluse.py |
Generate helpful docstrings for debugging | # -*- coding: utf-8 -*-
from agentscope.tool import ToolResponse
from agentscope.message import TextBlock
def create_memory_search_tool(memory_manager):
async def memory_search(
query: str,
max_results: int = 5,
min_score: float = 0.1,
) -> ToolResponse:
if memory_manager is N... | --- +++ @@ -1,15 +1,43 @@ # -*- coding: utf-8 -*-
+"""Memory search tool for semantic search in memory files."""
from agentscope.tool import ToolResponse
from agentscope.message import TextBlock
def create_memory_search_tool(memory_manager):
+ """Create a memory_search tool function with bound memory_manager.... | https://raw.githubusercontent.com/agentscope-ai/CoPaw/HEAD/src/copaw/agents/tools/memory_search.py |
Replace inline comments with docstrings | # -*- coding: utf-8 -*-
import asyncio
import logging
import os
import urllib.parse
import urllib.request
from pathlib import Path
from typing import Optional
from agentscope.message import Msg
from ...config import load_config
from ...constant import WORKING_DIR
from .file_handling import download_file_from_base64, ... | --- +++ @@ -1,4 +1,11 @@ # -*- coding: utf-8 -*-
+"""Message processing utilities for agent communication.
+
+This module handles:
+- File and media block processing
+- Message content manipulation
+- Message validation
+"""
import asyncio
import logging
import os
@@ -23,6 +30,7 @@
def _is_allowed_media_path(pat... | https://raw.githubusercontent.com/agentscope-ai/CoPaw/HEAD/src/copaw/agents/utils/message_processing.py |
Provide clean and structured docstrings | # -*- coding: utf-8 -*-
# flake8: noqa: E501
# pylint: disable=line-too-long
import re
from pathlib import Path
from typing import Optional
from agentscope.message import TextBlock
from agentscope.tool import ToolResponse
from ...constant import WORKING_DIR
from ...config.context import get_current_workspace_dir
fro... | --- +++ @@ -1,6 +1,7 @@ # -*- coding: utf-8 -*-
# flake8: noqa: E501
# pylint: disable=line-too-long
+"""File search tools: grep (content search) and glob (file discovery)."""
import re
from pathlib import Path
@@ -68,6 +69,7 @@
def _is_text_file(path: Path) -> bool:
+ """Heuristic check: skip known binary... | https://raw.githubusercontent.com/agentscope-ai/CoPaw/HEAD/src/copaw/agents/tools/file_search.py |
Add inline docstrings for readability | # -*- coding: utf-8 -*-
# flake8: noqa: E501
# pylint: disable=line-too-long
import asyncio
import locale
import os
import subprocess
import sys
from pathlib import Path
from typing import Optional
from agentscope.message import TextBlock
from agentscope.tool import ToolResponse
from ...constant import WORKING_DIR
f... | --- +++ @@ -1,6 +1,7 @@ # -*- coding: utf-8 -*-
# flake8: noqa: E501
# pylint: disable=line-too-long
+"""The shell command tool."""
import asyncio
import locale
@@ -19,6 +20,11 @@
def _kill_process_tree_win32(pid: int) -> None:
+ """Kill a process and all its descendants on Windows via taskkill.
+
+ Use... | https://raw.githubusercontent.com/agentscope-ai/CoPaw/HEAD/src/copaw/agents/tools/shell.py |
Generate docstrings with examples | # -*- coding: utf-8 -*-
import json
import os
import platform
import subprocess
import tempfile
import time
from agentscope.message import TextBlock
from agentscope.tool import ToolResponse
def _tool_error(msg: str) -> ToolResponse:
return ToolResponse(
content=[
TextBlock(
t... | --- +++ @@ -1,4 +1,5 @@ # -*- coding: utf-8 -*-
+"""Desktop/screen screenshot tool."""
import json
import os
@@ -46,6 +47,7 @@
def _capture_mss(path: str) -> ToolResponse:
+ """Full-screen capture using mss (Windows, Linux, macOS)."""
try:
import mss
except ImportError:
@@ -68,6 +70,7 @@ ... | https://raw.githubusercontent.com/agentscope-ai/CoPaw/HEAD/src/copaw/agents/tools/desktop_screenshot.py |
Add professional docstrings to my codebase | # -*- coding: utf-8 -*-
import logging
from datetime import datetime, timezone
from zoneinfo import ZoneInfo, ZoneInfoNotFoundError
from agentscope.message import TextBlock
from agentscope.tool import ToolResponse
from ...config import load_config, save_config
logger = logging.getLogger(__name__)
async def get_cu... | --- +++ @@ -1,4 +1,5 @@ # -*- coding: utf-8 -*-
+"""Tools for getting and setting the user timezone."""
import logging
from datetime import datetime, timezone
@@ -13,6 +14,14 @@
async def get_current_time() -> ToolResponse:
+ """Get the current time.
+ Only call this tool when the user explicitly asks for... | https://raw.githubusercontent.com/agentscope-ai/CoPaw/HEAD/src/copaw/agents/tools/get_current_time.py |
Add docstrings to improve collaboration | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
from __future__ import annotations
import argparse
import os
import random
import string
import subprocess
import sys
from pathlib import Path
REPO_ROOT = Path(__file__).resolve().parents[2]
ENV_PREFIX = "copaw_pack_"
# Packages affected by conda-unpack bug on Windows (... | --- +++ @@ -1,5 +1,9 @@ #!/usr/bin/env python3
# -*- coding: utf-8 -*-
+"""
+Create a temporary conda env, install CoPaw from a wheel, run conda-pack.
+Used by build_macos.sh and build_win.ps1. Run from repo root.
+"""
from __future__ import annotations
import argparse
@@ -26,6 +30,7 @@
def _conda_exe() -> str... | https://raw.githubusercontent.com/agentscope-ai/CoPaw/HEAD/scripts/pack/build_common.py |
Add docstrings following best practices | # -*- coding: utf-8 -*-
import asyncio
import logging
import os
from pathlib import Path
from typing import Any, List, Literal, Optional, Type, TYPE_CHECKING
from agentscope.agent import ReActAgent
from agentscope.mcp import HttpStatefulClient, StdIOStatefulClient
from agentscope.memory import InMemoryMemory
from agen... | --- +++ @@ -1,4 +1,9 @@ # -*- coding: utf-8 -*-
+"""CoPaw Agent - Main agent implementation.
+
+This module provides the main CoPawAgent class built on ReActAgent,
+with integrated tools, skills, and memory management.
+"""
import asyncio
import logging
import os
@@ -53,6 +58,24 @@
class CoPawAgent(ToolGuardMixi... | https://raw.githubusercontent.com/agentscope-ai/CoPaw/HEAD/src/copaw/agents/react_agent.py |
Document this module using docstrings | # -*- coding: utf-8 -*-
import logging
from typing import TYPE_CHECKING, Any
from agentscope.agent import ReActAgent
from agentscope.message import Msg, TextBlock
from copaw.constant import MEMORY_COMPACT_KEEP_RECENT
from ..utils import (
check_valid_messages,
safe_count_str_tokens,
)
if TYPE_CHECKING:
f... | --- +++ @@ -1,4 +1,10 @@ # -*- coding: utf-8 -*-
+"""Memory compaction hook for managing context window.
+
+This hook monitors token usage and automatically compacts older messages
+when the context window approaches its limit, preserving recent messages
+and the system prompt.
+"""
import logging
from typing import ... | https://raw.githubusercontent.com/agentscope-ai/CoPaw/HEAD/src/copaw/agents/hooks/memory_compaction.py |
Add docstrings including usage examples |
import os
import platform
import shutil
import socket
import subprocess
import tempfile
from pathlib import Path
def get_soffice_cmd() -> str:
# Prefer PATH first on all platforms.
path_cmd = shutil.which("soffice")
if path_cmd:
return path_cmd
if platform.system() == "Windows":
# Wi... | --- +++ @@ -1,3 +1,18 @@+"""
+Helper for running LibreOffice (soffice) in environments where AF_UNIX
+sockets may be blocked (e.g., sandboxed VMs). Detects the restriction
+at runtime and applies an LD_PRELOAD shim if needed.
+
+Usage:
+ from office.soffice import run_soffice, get_soffice_cmd, get_soffice_env
+
+ ... | https://raw.githubusercontent.com/agentscope-ai/CoPaw/HEAD/src/copaw/agents/skills/pptx/scripts/office/soffice.py |
Write Python docstrings for this snippet | # -*- coding: utf-8 -*-
import logging
import os
from pathlib import Path
from typing import Any, TYPE_CHECKING
from agentscope.token import HuggingFaceTokenCounter
if TYPE_CHECKING:
from copaw.config.config import AgentProfileConfig
logger = logging.getLogger(__name__)
class CopawTokenCounter(HuggingFaceToken... | --- +++ @@ -1,4 +1,9 @@ # -*- coding: utf-8 -*-
+"""Token counting utilities for CoPaw using HuggingFace tokenizers.
+
+This module provides a configurable token counter that supports dynamic
+switching between different tokenizer models based on runtime configuration.
+"""
import logging
import os
from pathlib impo... | https://raw.githubusercontent.com/agentscope-ai/CoPaw/HEAD/src/copaw/agents/utils/copaw_token_counter.py |
Write documentation strings for class attributes | # -*- coding: utf-8 -*-
from __future__ import annotations
import asyncio
import logging
from pathlib import Path
from typing import Any, Optional, TYPE_CHECKING
from ..config.config import load_agent_config
from ..config.utils import get_available_channels
if TYPE_CHECKING:
from ..config.config import ChannelC... | --- +++ @@ -1,4 +1,10 @@ # -*- coding: utf-8 -*-
+"""Watch agent.json for changes and auto-reload agent components.
+
+This watcher monitors an agent's workspace/agent.json file for changes
+and automatically reloads channels, heartbeat, and other configurations
+without requiring manual restart.
+"""
from __future_... | https://raw.githubusercontent.com/agentscope-ai/CoPaw/HEAD/src/copaw/app/agent_config_watcher.py |
Annotate my code with docstrings |
import os
import platform
import shutil
import socket
import subprocess
import tempfile
from pathlib import Path
def get_soffice_cmd() -> str:
# Prefer PATH first on all platforms.
path_cmd = shutil.which("soffice")
if path_cmd:
return path_cmd
if platform.system() == "Windows":
# Wi... | --- +++ @@ -1,3 +1,18 @@+"""
+Helper for running LibreOffice (soffice) in environments where AF_UNIX
+sockets may be blocked (e.g., sandboxed VMs). Detects the restriction
+at runtime and applies an LD_PRELOAD shim if needed.
+
+Usage:
+ from office.soffice import run_soffice, get_soffice_cmd, get_soffice_env
+
+ ... | https://raw.githubusercontent.com/agentscope-ai/CoPaw/HEAD/src/copaw/agents/skills/docx/scripts/office/soffice.py |
Generate docstrings for exported functions | # -*- coding: utf-8 -*-
from __future__ import annotations
import json
import logging
import os
import re
import time
import contextvars
import base64
import io
import zipfile
from dataclasses import dataclass
from pathlib import Path
from typing import Any
from urllib.parse import quote, urlencode, urlparse, unquote
... | --- +++ @@ -1,4 +1,5 @@ # -*- coding: utf-8 -*-
+"""Skills hub client and install helpers."""
from __future__ import annotations
import json
@@ -47,6 +48,7 @@
class SkillImportCancelled(RuntimeError):
+ """Raised when a skill import task is cancelled by user."""
RETRYABLE_HTTP_STATUS = {
@@ -472,6 +474,... | https://raw.githubusercontent.com/agentscope-ai/CoPaw/HEAD/src/copaw/agents/skills_hub.py |
Document all public functions with docstrings | # -*- coding: utf-8 -*-
from __future__ import annotations
import json as _json
import logging
from typing import Any, Literal
from agentscope.message import Msg
from ..security.tool_guard.models import TOOL_GUARD_DENIED_MARK
logger = logging.getLogger(__name__)
class ToolGuardMixin:
# ----------------------... | --- +++ @@ -1,4 +1,13 @@ # -*- coding: utf-8 -*-
+"""Tool-guard mixin for CoPawAgent.
+
+Provides ``_acting`` and ``_reasoning`` overrides that intercept
+sensitive tool calls before execution, implementing the deny /
+guard / approve flow.
+
+Separated from ``react_agent.py`` to keep the main agent class
+focused on l... | https://raw.githubusercontent.com/agentscope-ai/CoPaw/HEAD/src/copaw/agents/tool_guard_mixin.py |
Fully document this Python code with docstrings | # -*- coding: utf-8 -*-
from typing import Literal, Optional
from typing_extensions import TypedDict, Required
from agentscope.message import Base64Source, URLSource
class FileBlock(TypedDict, total=False):
type: Required[Literal["file"]]
"""The type of the block"""
source: Required[Base64Source | URLS... | --- +++ @@ -1,4 +1,7 @@ # -*- coding: utf-8 -*-
+"""
+Agent tools schema: type definitions for agent tool responses.
+"""
from typing import Literal, Optional
from typing_extensions import TypedDict, Required
@@ -6,6 +9,7 @@
class FileBlock(TypedDict, total=False):
+ """File block for sending files to users.... | https://raw.githubusercontent.com/agentscope-ai/CoPaw/HEAD/src/copaw/agents/schema.py |
Add clean documentation to messy code | # -*- coding: utf-8 -*-
# flake8: noqa: E501
import asyncio
import atexit
from concurrent import futures
import json
import logging
import os
import subprocess
import sys
import time
from typing import Any, Optional
from agentscope.message import TextBlock
from agentscope.tool import ToolResponse
from ...config impo... | --- +++ @@ -1,5 +1,13 @@ # -*- coding: utf-8 -*-
# flake8: noqa: E501
+"""Browser automation tool using Playwright.
+
+Single tool with action-based API matching browser MCP: start, stop, open,
+navigate, navigate_back, screenshot, snapshot, click, type, eval, evaluate,
+resize, console_messages, handle_dialog, file_u... | https://raw.githubusercontent.com/agentscope-ai/CoPaw/HEAD/src/copaw/agents/tools/browser_control.py |
Document this code for team use | # -*- coding: utf-8 -*-
import logging
from pathlib import Path
logger = logging.getLogger(__name__)
_token_counter = None
def _get_token_counter():
global _token_counter
if _token_counter is None:
from agentscope.token import HuggingFaceTokenCounter
# Use Qwen tokenizer for DashScope model... | --- +++ @@ -1,4 +1,9 @@ # -*- coding: utf-8 -*-
+"""Token counting utilities for managing context windows.
+
+This module provides token counting functionality for estimating
+message token usage with Qwen tokenizer.
+"""
import logging
from pathlib import Path
@@ -8,6 +13,14 @@
def _get_token_counter():
+ "... | https://raw.githubusercontent.com/agentscope-ai/CoPaw/HEAD/src/copaw/agents/utils/token_counting.py |
Add docstrings to my Python code | # -*- coding: utf-8 -*-
# Default truncation limits
DEFAULT_MAX_LINES = 1000
DEFAULT_MAX_BYTES = 30 * 1024 # 30KB
# pylint: disable=too-many-branches
def truncate_output(
text: str,
max_lines: int = DEFAULT_MAX_LINES,
max_bytes: int = DEFAULT_MAX_BYTES,
keep: str = "head",
) -> tuple[str, bool, int,... | --- +++ @@ -1,4 +1,5 @@ # -*- coding: utf-8 -*-
+"""Shared utilities for file and shell tools."""
# Default truncation limits
DEFAULT_MAX_LINES = 1000
@@ -12,6 +13,17 @@ max_bytes: int = DEFAULT_MAX_BYTES,
keep: str = "head",
) -> tuple[str, bool, int, str]:
+ """Smart truncation for large content.
+
+... | https://raw.githubusercontent.com/agentscope-ai/CoPaw/HEAD/src/copaw/agents/tools/utils.py |
Generate docstrings with parameter types | # -*- coding: utf-8 -*-
import logging
from pathlib import Path
from typing import Any
from ..prompt import build_bootstrap_guidance
from ..utils import (
is_first_user_interaction,
prepend_to_message_content,
)
logger = logging.getLogger(__name__)
class BootstrapHook:
def __init__(
self,
... | --- +++ @@ -1,4 +1,9 @@ # -*- coding: utf-8 -*-
+"""Bootstrap hook for first-time user interaction guidance.
+
+This hook checks for BOOTSTRAP.md on the first user interaction and
+prepends guidance to help set up the agent's identity and preferences.
+"""
import logging
from pathlib import Path
from typing import A... | https://raw.githubusercontent.com/agentscope-ai/CoPaw/HEAD/src/copaw/agents/hooks/bootstrap.py |
Write docstrings for utility functions | # -*- coding: utf-8 -*-
from __future__ import annotations
import logging
from dataclasses import dataclass, field
from typing import Any, AsyncGenerator, Literal, Type
from agentscope.formatter import FormatterBase
from agentscope.model import ChatModelBase
from agentscope.model._model_response import ChatResponse
... | --- +++ @@ -1,4 +1,5 @@ # -*- coding: utf-8 -*-
+"""ChatModel router for local/cloud model selection."""
from __future__ import annotations
@@ -26,6 +27,7 @@
class RoutingPolicy:
+ """Select a route using the configured default mode."""
def __init__(self, cfg: AgentsLLMRoutingConfig):
self.c... | https://raw.githubusercontent.com/agentscope-ai/CoPaw/HEAD/src/copaw/agents/routing_chat_model.py |
Add docstrings that explain inputs and outputs | # -*- coding: utf-8 -*-
# flake8: noqa: E501
# pylint: disable=line-too-long
import os
from pathlib import Path
from typing import Optional
from agentscope.message import TextBlock
from agentscope.tool import ToolResponse
from ...constant import WORKING_DIR
from ...config.context import get_current_workspace_dir
from... | --- +++ @@ -14,6 +14,15 @@
def _resolve_file_path(file_path: str) -> str:
+ """Resolve file path: use absolute path as-is,
+ resolve relative path from current workspace or WORKING_DIR.
+
+ Args:
+ file_path: The input file path (absolute or relative).
+
+ Returns:
+ The resolved absolute ... | https://raw.githubusercontent.com/agentscope-ai/CoPaw/HEAD/src/copaw/agents/tools/file_io.py |
Create documentation for each function signature | # -*- coding: utf-8 -*-
# pylint: disable=redefined-outer-name,unused-argument
import mimetypes
import os
import time
from contextlib import asynccontextmanager
from pathlib import Path
from fastapi import FastAPI, HTTPException
from fastapi.middleware.cors import CORSMiddleware
from fastapi.staticfiles import StaticF... | --- +++ @@ -47,15 +47,22 @@
# Dynamic runner that selects the correct workspace runner based on request
class DynamicMultiAgentRunner:
+ """Runner wrapper that dynamically routes to the correct workspace runner.
+
+ This allows AgentApp to work with multiple agents by inspecting
+ the X-Agent-Id header on e... | https://raw.githubusercontent.com/agentscope-ai/CoPaw/HEAD/src/copaw/app/_app.py |
Write docstrings for this repository | # -*- coding: utf-8 -*-
import logging
from typing import List, Sequence, Tuple, Type, Any, Union, Optional
from agentscope.formatter import FormatterBase, OpenAIChatFormatter
from agentscope.model import ChatModelBase, OpenAIChatModel
try:
from agentscope.formatter import AnthropicChatFormatter
from agents... | --- +++ @@ -1,4 +1,13 @@ # -*- coding: utf-8 -*-
+"""Factory for creating chat models and formatters.
+
+This module provides a unified factory for creating chat model instances
+and their corresponding formatters based on configuration.
+
+Example:
+ >>> from copaw.agents.model_factory import create_model_and_forma... | https://raw.githubusercontent.com/agentscope-ai/CoPaw/HEAD/src/copaw/agents/model_factory.py |
Create docstrings for each class method | # -*- coding: utf-8 -*-
from datetime import date, timedelta
from agentscope.message import TextBlock
from agentscope.tool import ToolResponse
from ...token_usage import get_token_usage_manager
async def get_token_usage(
days: int = 30,
model_name: str | None = None,
provider_id: str | None = None,
) -... | --- +++ @@ -1,4 +1,5 @@ # -*- coding: utf-8 -*-
+"""Tool to query token usage statistics."""
from datetime import date, timedelta
@@ -13,6 +14,19 @@ model_name: str | None = None,
provider_id: str | None = None,
) -> ToolResponse:
+ """Query LLM token usage over the past N days.
+
+ Use this when t... | https://raw.githubusercontent.com/agentscope-ai/CoPaw/HEAD/src/copaw/agents/tools/get_token_usage.py |
Create structured documentation for my script | # -*- coding: utf-8 -*-
from datetime import datetime
from pathlib import Path
class AgentMdManager:
def __init__(self, working_dir: str | Path):
self.working_dir: Path = Path(working_dir)
self.working_dir.mkdir(parents=True, exist_ok=True)
self.memory_dir: Path = self.working_dir / "memo... | --- +++ @@ -1,17 +1,31 @@ # -*- coding: utf-8 -*-
+"""Agent markdown manager for reading and writing markdown files in working
+and memory directories."""
from datetime import datetime
from pathlib import Path
class AgentMdManager:
+ """Manager for reading and writing markdown files in working and memory
+ ... | https://raw.githubusercontent.com/agentscope-ai/CoPaw/HEAD/src/copaw/agents/memory/agent_md_manager.py |
Write beginner-friendly docstrings | # -*- coding: utf-8 -*-
# flake8: noqa: E501
import logging
from pathlib import Path
logger = logging.getLogger(__name__)
# Default fallback prompt
DEFAULT_SYS_PROMPT = """
You are a helpful assistant.
"""
# Backward compatibility alias
SYS_PROMPT = DEFAULT_SYS_PROMPT
class PromptConfig:
# Default files to lo... | --- +++ @@ -1,5 +1,10 @@ # -*- coding: utf-8 -*-
# flake8: noqa: E501
+"""System prompt building utilities.
+
+This module provides utilities for building system prompts from
+markdown configuration files in the working directory.
+"""
import logging
from pathlib import Path
@@ -15,6 +20,7 @@
class PromptConfi... | https://raw.githubusercontent.com/agentscope-ai/CoPaw/HEAD/src/copaw/agents/prompt.py |
Write docstrings for data processing functions | # -*- coding: utf-8 -*-
import json
import logging
from pathlib import Path
from typing import TYPE_CHECKING
from agentscope.agent._react_agent import _MemoryMark
from agentscope.message import Msg, TextBlock
from ..constant import DEBUG_HISTORY_FILE, MAX_LOAD_HISTORY_COUNT
if TYPE_CHECKING:
from .memory import ... | --- +++ @@ -1,4 +1,8 @@ # -*- coding: utf-8 -*-
+"""Agent command handler for system commands.
+
+This module handles system commands like /compact, /new, /clear, etc.
+"""
import json
import logging
from pathlib import Path
@@ -18,6 +22,11 @@
class ConversationCommandHandlerMixin:
+ """Mixin for conversation... | https://raw.githubusercontent.com/agentscope-ai/CoPaw/HEAD/src/copaw/agents/command_handler.py |
Add docstrings to make code maintainable | # -*- coding: utf-8 -*-
import re
from typing import Any
INTERACTIVE_ROLES = frozenset(
{
"button",
"link",
"textbox",
"checkbox",
"radio",
"combobox",
"listbox",
"menuitem",
"menuitemcheckbox",
"menuitemradio",
"option",
... | --- +++ @@ -1,4 +1,5 @@ # -*- coding: utf-8 -*-
+"""Build role snapshot + refs from Playwright aria_snapshot."""
import re
from typing import Any
@@ -188,6 +189,7 @@ compact: bool = False,
max_depth: int | None = None,
) -> tuple[str, dict[str, dict]]:
+ """Build snapshot + refs from Playwright locator... | https://raw.githubusercontent.com/agentscope-ai/CoPaw/HEAD/src/copaw/agents/tools/browser_snapshot.py |
Add detailed documentation for each class | # -*- coding: utf-8 -*-
import logging
import shutil
from pathlib import Path
logger = logging.getLogger(__name__)
def copy_md_files(
language: str,
skip_existing: bool = False,
workspace_dir: Path | None = None,
) -> list[str]:
from ...constant import WORKING_DIR
# Use provided workspace_dir or... | --- +++ @@ -1,4 +1,9 @@ # -*- coding: utf-8 -*-
+"""Setup and initialization utilities for agent configuration.
+
+This module handles copying markdown configuration files to
+the working directory.
+"""
import logging
import shutil
from pathlib import Path
@@ -11,6 +16,16 @@ skip_existing: bool = False,
wo... | https://raw.githubusercontent.com/agentscope-ai/CoPaw/HEAD/src/copaw/agents/utils/setup_utils.py |
Write docstrings describing functionality | # -*- coding: utf-8 -*-
import os
import mimetypes
import base64
import hashlib
import logging
import subprocess
import urllib.parse
import urllib.request
from pathlib import Path
from typing import Optional
logger = logging.getLogger(__name__)
def _resolve_local_path(
url: str,
parsed: urllib.parse.ParseRes... | --- +++ @@ -1,4 +1,11 @@ # -*- coding: utf-8 -*-
+"""File handling utilities for downloading and managing files.
+
+This module provides utilities for:
+- Downloading files from base64 encoded data
+- Downloading files from URLs
+- Managing download directories
+"""
import os
import mimetypes
import base64
@@ -17,6 ... | https://raw.githubusercontent.com/agentscope-ai/CoPaw/HEAD/src/copaw/agents/utils/file_handling.py |
Add detailed docstrings explaining each function | # -*- coding: utf-8 -*-
# pylint: disable=too-many-branches
import asyncio
import logging
import os
import platform
from typing import TYPE_CHECKING
from agentscope.formatter import FormatterBase
from agentscope.message import Msg
from agentscope.model import ChatModelBase
from agentscope.tool import Toolkit, ToolResp... | --- +++ @@ -1,5 +1,13 @@ # -*- coding: utf-8 -*-
# pylint: disable=too-many-branches
+"""Memory Manager for CoPaw agents.
+
+Extends ReMeLight to provide memory management capabilities including:
+- Message compaction with configurable ratio
+- Memory summarization with tool support
+- Vector and full-text search inte... | https://raw.githubusercontent.com/agentscope-ai/CoPaw/HEAD/src/copaw/agents/memory/memory_manager.py |
Add docstrings explaining edge cases | # -*- coding: utf-8 -*-
import json
import logging
logger = logging.getLogger(__name__)
def extract_tool_ids(msg) -> tuple[set[str], set[str]]:
uses: set[str] = set()
results: set[str] = set()
if isinstance(msg.content, list):
for block in msg.content:
if isinstance(block, dict) and b... | --- +++ @@ -1,4 +1,9 @@ # -*- coding: utf-8 -*-
+"""Tool message validation and sanitization utilities.
+
+This module ensures tool_use and tool_result messages are properly
+paired and ordered to prevent API errors.
+"""
import json
import logging
@@ -6,6 +11,14 @@
def extract_tool_ids(msg) -> tuple[set[str], ... | https://raw.githubusercontent.com/agentscope-ai/CoPaw/HEAD/src/copaw/agents/utils/tool_message_utils.py |
Generate descriptive docstrings automatically | # -*- coding: utf-8 -*-
import asyncio
import logging
import shutil
import threading
from typing import List, Optional, Tuple
logger = logging.getLogger(__name__)
# ------------------------------------------------------------------
# Cached local-whisper model (lazy singleton)
# -------------------------------------... | --- +++ @@ -1,4 +1,13 @@ # -*- coding: utf-8 -*-
+"""Audio transcription utility.
+
+Transcribes audio files to text using either:
+- An OpenAI-compatible ``/v1/audio/transcriptions`` endpoint (Whisper API), or
+- The locally installed ``openai-whisper`` Python library (Local Whisper).
+
+Transcription is only attempte... | https://raw.githubusercontent.com/agentscope-ai/CoPaw/HEAD/src/copaw/agents/utils/audio_transcription.py |
Fill in missing docstrings in my code | # -*- coding: utf-8 -*-
from contextvars import ContextVar
from typing import Optional, TYPE_CHECKING
from fastapi import Request
from .multi_agent_manager import MultiAgentManager
from ..config.utils import load_config
if TYPE_CHECKING:
from .workspace import Workspace
# Context variable to store current agent I... | --- +++ @@ -1,4 +1,8 @@ # -*- coding: utf-8 -*-
+"""Agent context utilities for multi-agent support.
+
+Provides utilities to get the correct agent instance for each request.
+"""
from contextvars import ContextVar
from typing import Optional, TYPE_CHECKING
from fastapi import Request
@@ -19,6 +23,24 @@ request:... | https://raw.githubusercontent.com/agentscope-ai/CoPaw/HEAD/src/copaw/app/agent_context.py |
Document all public functions with docstrings | # -*- coding: utf-8 -*-
import mimetypes
import os
import unicodedata
from pathlib import Path
from agentscope.message import ImageBlock, TextBlock
from agentscope.tool import ToolResponse
_IMAGE_EXTENSIONS = {
".png",
".jpg",
".jpeg",
".gif",
".webp",
".bmp",
".tiff",
".tif",
}
asy... | --- +++ @@ -1,4 +1,5 @@ # -*- coding: utf-8 -*-
+"""Load an image file into the LLM context for visual analysis."""
import mimetypes
import os
@@ -21,6 +22,19 @@
async def view_image(image_path: str) -> ToolResponse:
+ """Load an image file into the LLM context so the model can see it.
+
+ Use this after ... | https://raw.githubusercontent.com/agentscope-ai/CoPaw/HEAD/src/copaw/agents/tools/view_image.py |
Add docstrings to improve code quality | # -*- coding: utf-8 -*-
import logging
import shutil
from pathlib import Path
from typing import Any
from pydantic import BaseModel
import frontmatter
from packaging.version import Version
logger = logging.getLogger(__name__)
def _dedupe_skills_by_name(skills: list["SkillInfo"]) -> list["SkillInfo"]:
merged: d... | --- +++ @@ -1,4 +1,5 @@ # -*- coding: utf-8 -*-
+"""Skills management: sync skills from code to working_dir."""
import logging
import shutil
@@ -13,6 +14,7 @@
def _dedupe_skills_by_name(skills: list["SkillInfo"]) -> list["SkillInfo"]:
+ """Return one skill per name, preferring customized over builtin."""
... | https://raw.githubusercontent.com/agentscope-ai/CoPaw/HEAD/src/copaw/agents/skills_manager.py |
Provide docstrings following PEP 257 |
import json
import os
import platform
import subprocess
import sys
from pathlib import Path
from office.soffice import get_soffice_cmd, get_soffice_env
from openpyxl import load_workbook
MACRO_DIR_MACOS = "~/Library/Application Support/LibreOffice/4/user/basic/Standard"
MACRO_DIR_LINUX = "~/.config/libreoffice/4/us... | --- +++ @@ -1,3 +1,7 @@+"""
+Excel Formula Recalculation Script
+Recalculates all formulas in an Excel file using LibreOffice
+"""
import json
import os
@@ -37,6 +41,7 @@
def _get_macro_dir() -> str:
+ """Return the LibreOffice macro directory for the current platform."""
system = platform.system()
... | https://raw.githubusercontent.com/agentscope-ai/CoPaw/HEAD/src/copaw/agents/skills/xlsx/scripts/recalc.py |
Add docstrings to improve readability | # -*- coding: utf-8 -*-
# pylint:disable=too-many-return-statements
from __future__ import annotations
import logging
import os
import time
import sqlite3
import subprocess
import threading
import shutil
import asyncio
import base64
import hashlib
from pathlib import Path
from typing import Any, Dict, Optional, List
... | --- +++ @@ -167,6 +167,7 @@ result.check_returncode()
def _emit_request_threadsafe(self, request: Any) -> None:
+ """Enqueue request via manager (thread-safe)."""
if self._enqueue is not None:
self._enqueue(request)
@@ -245,6 +246,7 @@ logger.info("watcher t... | https://raw.githubusercontent.com/agentscope-ai/CoPaw/HEAD/src/copaw/app/channels/imessage/channel.py |
Document my Python code with docstrings | # -*- coding: utf-8 -*-
# pylint: disable=too-many-branches,too-many-statements
from __future__ import annotations
import json
import logging
from dataclasses import dataclass
from typing import Any, List, Union
from agentscope_runtime.engine.schemas.agent_schemas import (
AudioContent,
ContentType,
FileC... | --- +++ @@ -1,5 +1,9 @@ # -*- coding: utf-8 -*-
# pylint: disable=too-many-branches,too-many-statements
+"""
+Pluggable message renderer: Message -> sendable parts (runtime Content).
+Style/capabilities control markdown, emoji, code fence.
+"""
from __future__ import annotations
import json
@@ -32,6 +36,7 @@
@da... | https://raw.githubusercontent.com/agentscope-ai/CoPaw/HEAD/src/copaw/app/channels/renderer.py |
Add clean documentation to messy code | # -*- coding: utf-8 -*-
# pylint: disable=protected-access
# ChannelManager is the framework owner of BaseChannel and must call
# _is_native_payload and _consume_one_request as part of the contract.
from __future__ import annotations
import asyncio
import logging
from pathlib import Path
from typing import (
Cal... | --- +++ @@ -45,6 +45,7 @@ key: str,
first_payload: Any,
) -> List[Any]:
+ """Drain queue of payloads with same debounce key; return batch."""
batch = [first_payload]
put_back: List[Any] = []
while True:
@@ -62,6 +63,7 @@
async def _process_batch(ch: BaseChannel, batch: List[Any]) -> None... | https://raw.githubusercontent.com/agentscope-ai/CoPaw/HEAD/src/copaw/app/channels/manager.py |
Add docstrings to existing functions | # -*- coding: utf-8 -*-
from __future__ import annotations
from dataclasses import dataclass
from typing import Any, Dict, Optional, Protocol, runtime_checkable
@dataclass
class ChannelAddress:
kind: str # "dm" | "channel" | "webhook" | "console" | ...
id: str
extra: Optional[Dict[str, Any]] = None
... | --- +++ @@ -1,4 +1,8 @@ # -*- coding: utf-8 -*-
+"""
+Channel schema: channel type identifiers, routing (ChannelAddress),
+and conversion protocol.
+"""
from __future__ import annotations
from dataclasses import dataclass
@@ -7,12 +11,17 @@
@dataclass
class ChannelAddress:
+ """
+ Unified routing for send:... | https://raw.githubusercontent.com/agentscope-ai/CoPaw/HEAD/src/copaw/app/channels/schema.py |
Add docstrings to my Python code | # -*- coding: utf-8 -*-
# pylint: disable=too-many-instance-attributes,too-many-arguments
from __future__ import annotations
import asyncio
import json
import logging
import re
import uuid
from pathlib import Path
from typing import Any, Optional, Union
import httpx
from agentscope_runtime.engine.schemas.agent_schema... | --- +++ @@ -1,5 +1,6 @@ # -*- coding: utf-8 -*-
# pylint: disable=too-many-instance-attributes,too-many-arguments
+"""Mattermost channel: WebSocket event listener + REST API replies."""
from __future__ import annotations
import asyncio
@@ -47,6 +48,7 @@ media_dir: Path,
filename_hint: str = "",
) -> Opti... | https://raw.githubusercontent.com/agentscope-ai/CoPaw/HEAD/src/copaw/app/channels/mattermost/channel.py |
Add docstrings for better understanding | # -*- coding: utf-8 -*-
# pylint: disable=too-many-branches,too-many-statements,unused-argument
# pylint: disable=too-many-public-methods,unnecessary-pass
from __future__ import annotations
import asyncio
import logging
from abc import ABC
from typing import (
Optional,
Dict,
Any,
List,
Union,
... | --- +++ @@ -1,6 +1,9 @@ # -*- coding: utf-8 -*-
# pylint: disable=too-many-branches,too-many-statements,unused-argument
# pylint: disable=too-many-public-methods,unnecessary-pass
+"""
+Base Channel: bound to AgentRequest/AgentResponse, unified by process.
+"""
from __future__ import annotations
import asyncio
@@ ... | https://raw.githubusercontent.com/agentscope-ai/CoPaw/HEAD/src/copaw/app/channels/base.py |
Add docstrings explaining edge cases | # -*- coding: utf-8 -*-
# pylint: disable=too-many-branches,too-many-statements
from __future__ import annotations
import logging
import os
import sys
import json
from datetime import datetime
from pathlib import Path
from typing import Any, AsyncGenerator, Dict, List, Optional, Union
from agentscope_runtime.engine.s... | --- +++ @@ -1,5 +1,14 @@ # -*- coding: utf-8 -*-
# pylint: disable=too-many-branches,too-many-statements
+"""Console Channel.
+
+A lightweight channel that prints all agent responses to stdout.
+
+Messages are sent to the agent via the standard AgentApp ``/agent/process``
+endpoint or via POST /console/chat. This chan... | https://raw.githubusercontent.com/agentscope-ai/CoPaw/HEAD/src/copaw/app/channels/console/channel.py |
Help me add docstrings to my project | # -*- coding: utf-8 -*-
import asyncio
import logging
import mimetypes
import tempfile
from pathlib import Path
from typing import Any, Dict, List, Optional
from urllib.parse import urlparse
import aiohttp
from agentscope_runtime.engine.schemas.agent_schemas import (
AgentRequest,
AudioContent,
ContentTyp... | --- +++ @@ -1,4 +1,5 @@ # -*- coding: utf-8 -*-
+"""Matrix channel implementation using matrix-nio."""
import asyncio
import logging
@@ -85,6 +86,7 @@ self._sync_task: Optional[asyncio.Task] = None
def _mxc_to_http(self, mxc_url: str) -> str:
+ """Convert mxc://server/media_id to an authentica... | https://raw.githubusercontent.com/agentscope-ai/CoPaw/HEAD/src/copaw/app/channels/matrix/channel.py |
Generate docstrings for script automation | # -*- coding: utf-8 -*-
from __future__ import annotations
import asyncio
import logging
import time
import uuid
from dataclasses import dataclass, field
from typing import TYPE_CHECKING, Any
from ...security.tool_guard.approval import ApprovalDecision
if TYPE_CHECKING:
from ...security.tool_guard.models import ... | --- +++ @@ -1,4 +1,10 @@ # -*- coding: utf-8 -*-
+"""Approval service for sensitive tool execution.
+
+The ``ApprovalService`` is the single central store for pending /
+completed approval records. Approval is granted exclusively via
+the ``/daemon approve`` command in the chat interface.
+"""
from __future__ import ... | https://raw.githubusercontent.com/agentscope-ai/CoPaw/HEAD/src/copaw/app/approvals/service.py |
Add verbose docstrings with examples | # -*- coding: utf-8 -*-
from __future__ import annotations
import asyncio
import logging
from functools import partial
logger = logging.getLogger(__name__)
class TwilioManager:
def __init__(self, account_sid: str, auth_token: str) -> None:
self._account_sid = account_sid
self._auth_token = auth... | --- +++ @@ -1,4 +1,5 @@ # -*- coding: utf-8 -*-
+"""Twilio API wrapper for the Voice channel."""
from __future__ import annotations
import asyncio
@@ -9,6 +10,7 @@
class TwilioManager:
+ """Async wrapper around the synchronous ``twilio`` Python SDK."""
def __init__(self, account_sid: str, auth_token: ... | https://raw.githubusercontent.com/agentscope-ai/CoPaw/HEAD/src/copaw/app/channels/voice/twilio_manager.py |
Add professional docstrings to my codebase | # -*- coding: utf-8 -*-
from __future__ import annotations
import importlib
import logging
import sys
import threading
from typing import TYPE_CHECKING
from ...constant import CUSTOM_CHANNELS_DIR
from .base import BaseChannel
if TYPE_CHECKING:
pass
logger = logging.getLogger(__name__)
_BUILTIN_SPECS: dict[str,... | --- +++ @@ -1,4 +1,5 @@ # -*- coding: utf-8 -*-
+"""Channel registry: built-in + custom channels from working dir."""
from __future__ import annotations
import importlib
@@ -39,6 +40,10 @@
def _load_builtin_channels() -> dict[str, type[BaseChannel]]:
+ """Load built-in channels safely.
+
+ A single option... | https://raw.githubusercontent.com/agentscope-ai/CoPaw/HEAD/src/copaw/app/channels/registry.py |
Add verbose docstrings with examples | # -*- coding: utf-8 -*-
from __future__ import annotations
import json
import logging
import threading
from typing import Any, Optional, Union
import paho.mqtt.client as mqtt
from paho.mqtt import MQTTException
from agentscope_runtime.engine.schemas.agent_schemas import (
TextContent,
ContentType,
)
from ..... | --- +++ @@ -1,4 +1,5 @@ # -*- coding: utf-8 -*-
+"""MQTT Channel for IoT devices and robots"""
from __future__ import annotations
import json
@@ -26,6 +27,7 @@
class MQTTChannel(BaseChannel):
+ """MQTT Channel for IoT devices and robots"""
channel = "mqtt"
uses_manager_queue = True
@@ -192,6 +194... | https://raw.githubusercontent.com/agentscope-ai/CoPaw/HEAD/src/copaw/app/channels/mqtt/channel.py |
Add docstrings with type hints explained | # -*- coding: utf-8 -*-
from __future__ import annotations
import xml.etree.ElementTree as ET
def build_conversation_relay_twiml(
ws_url: str,
*,
welcome_greeting: str = "Hi! This is CoPaw. How can I help you?",
tts_provider: str = "google",
tts_voice: str = "en-US-Journey-D",
stt_provider: s... | --- +++ @@ -1,4 +1,5 @@ # -*- coding: utf-8 -*-
+"""TwiML generation helpers for the Voice channel."""
from __future__ import annotations
import xml.etree.ElementTree as ET
@@ -14,6 +15,11 @@ language: str = "en-US",
interruptible: bool = True,
) -> str:
+ """Build TwiML ``<Response>`` that connects to... | https://raw.githubusercontent.com/agentscope-ai/CoPaw/HEAD/src/copaw/app/channels/voice/twiml.py |
Add docstrings explaining edge cases | # -*- coding: utf-8 -*-
# pylint: disable=too-many-branches,too-many-statements
from __future__ import annotations
import asyncio
import json
import logging
import os
import re
import threading
import time
from pathlib import Path
from typing import Any, Dict, List, Optional
import aiofiles
import aiohttp
from agen... | --- +++ @@ -1,5 +1,13 @@ # -*- coding: utf-8 -*-
# pylint: disable=too-many-branches,too-many-statements
+"""QQ Channel.
+
+QQ uses WebSocket for incoming events and HTTP API for replies.
+No request-reply coupling: handler enqueues Incoming, consumer processes
+and sends reply via send_c2c_message / send_channel_mess... | https://raw.githubusercontent.com/agentscope-ai/CoPaw/HEAD/src/copaw/app/channels/qq/channel.py |
Generate docstrings for this script | # -*- coding: utf-8 -*-
from __future__ import annotations
import hashlib
import hmac
import json
import logging
import os
import secrets
import time
from typing import Optional
from fastapi import Request, Response
from starlette.middleware.base import BaseHTTPMiddleware
from ..constant import SECRET_DIR
logger = ... | --- +++ @@ -1,4 +1,20 @@ # -*- coding: utf-8 -*-
+"""Authentication module: password hashing, JWT tokens, and FastAPI middleware.
+
+Login is disabled by default and only enabled when the environment
+variable ``COPAW_AUTH_ENABLED`` is set to a truthy value (``true``,
+``1``, ``yes``). Credentials are created through ... | https://raw.githubusercontent.com/agentscope-ai/CoPaw/HEAD/src/copaw/app/auth.py |
Write docstrings for data processing functions | # -*- coding: utf-8 -*-
# pylint: disable=too-many-statements,too-many-branches
# pylint: disable=too-many-return-statements,too-many-instance-attributes
# pylint: disable=too-many-nested-blocks
from __future__ import annotations
import asyncio
import hashlib
import logging
import os
import sys
import threading
from ... | --- +++ @@ -2,6 +2,12 @@ # pylint: disable=too-many-statements,too-many-branches
# pylint: disable=too-many-return-statements,too-many-instance-attributes
# pylint: disable=too-many-nested-blocks
+"""WeCom (Enterprise WeChat) Channel.
+
+Uses the aibot WebSocket SDK to receive messages from WeCom AI Bot.
+Sends repli... | https://raw.githubusercontent.com/agentscope-ai/CoPaw/HEAD/src/copaw/app/channels/wecom/channel.py |
Help me document legacy Python code | # -*- coding: utf-8 -*-
# pylint: disable=too-many-branches,too-many-statements
from __future__ import annotations
import os
import logging
import asyncio
import re
import tempfile
from pathlib import Path
from urllib.parse import urlparse
from typing import Any, Optional
import aiohttp
from agentscope_runtime.engine... | --- +++ @@ -284,6 +284,7 @@ )
async def _resolve_target(self, to_handle, _meta):
+ """Resolve a Discord Messageable from meta or to_handle."""
route = self._route_from_handle(to_handle)
channel_id = route.get("channel_id")
user_id = route.get("user_id")
@@ -303,6 +304,16... | https://raw.githubusercontent.com/agentscope-ai/CoPaw/HEAD/src/copaw/app/channels/discord_/channel.py |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.