instruction stringclasses 100
values | code stringlengths 78 193k | response stringlengths 259 170k | file stringlengths 59 203 |
|---|---|---|---|
Write proper docstrings for these functions | from typing import Any, Dict, List, Optional, Union
class GraphSearch:
def __init__(self, graph: Dict[str, List[str]]) -> None:
self.graph = graph
def find_path_dfs(
self, start: str, end: str, path: Optional[List[str]] = None
) -> Optional[List[str]]:
path = path or []
... | --- +++ @@ -2,6 +2,11 @@
class GraphSearch:
+ """Graph search emulation in python, from source
+ http://www.python.org/doc/essays/graphs/
+
+ dfs stands for Depth First Search
+ bfs stands for Breadth First Search"""
def __init__(self, graph: Dict[str, List[str]]) -> None:
self.graph = g... | https://raw.githubusercontent.com/faif/python-patterns/HEAD/patterns/other/graph_search.py |
Add well-formatted docstrings |
__author__ = "Ibrahim Diop <ibrahim@sikilabs.com>"
class Catalog:
def __init__(self, param: str) -> None:
# dictionary that will be used to determine which static method is
# to be executed but that will be also used to store possible param
# value
self._static_method_choices = ... | --- +++ @@ -1,9 +1,15 @@+"""
+A class that uses different static functions depending on a parameter passed
+during initialization. Uses a single dictionary instead of multiple conditions.
+"""
__author__ = "Ibrahim Diop <ibrahim@sikilabs.com>"
class Catalog:
+ """catalog of multiple static methods that are... | https://raw.githubusercontent.com/faif/python-patterns/HEAD/patterns/behavioral/catalog.py |
Write reusable docstrings |
# Complex computer parts
class CPU:
def freeze(self) -> None:
print("Freezing processor.")
def jump(self, position: str) -> None:
print("Jumping to:", position)
def execute(self) -> None:
print("Executing.")
class Memory:
def load(self, position: str, data: str) -> None:
... | --- +++ @@ -1,7 +1,39 @@+"""
+Example from https://en.wikipedia.org/wiki/Facade_pattern#Python
+
+
+*What is this pattern about?
+The Facade pattern is a way to provide a simpler unified interface to
+a more complex system. It provides an easier way to access functions
+of the underlying system by providing a single en... | https://raw.githubusercontent.com/faif/python-patterns/HEAD/patterns/structural/facade.py |
Fully document this Python code with docstrings |
def get_text() -> str:
return "plain-text"
def get_pdf() -> str:
return "pdf"
def get_csv() -> str:
return "csv"
def convert_to_text(data: str) -> str:
print("[CONVERT]")
return f"{data} as text"
def saver() -> None:
print("[SAVE]")
def template_function(getter, converter=False, to_s... | --- +++ @@ -1,3 +1,13 @@+"""
+An example of the Template pattern in Python
+
+*TL;DR
+Defines the skeleton of a base algorithm, deferring definition of exact
+steps to subclasses.
+
+*Examples in Python ecosystem:
+Django class based views: https://docs.djangoproject.com/en/2.1/topics/class-based-views/
+"""
def g... | https://raw.githubusercontent.com/faif/python-patterns/HEAD/patterns/behavioral/template.py |
Write docstrings for backend logic | from queue import Queue
from types import TracebackType
from typing import Union
class ObjectPool:
def __init__(self, queue: Queue, auto_get: bool = False) -> None:
self._queue = queue
self.item = self._queue.get() if auto_get else None
def __enter__(self) -> str:
if self.item is None... | --- +++ @@ -1,3 +1,32 @@+"""
+*What is this pattern about?
+This pattern is used when creating an object is costly (and they are
+created frequently) but only a few are used at a time. With a Pool we
+can manage those instances we have as of now by caching them. Now it
+is possible to skip the costly creation of an obj... | https://raw.githubusercontent.com/faif/python-patterns/HEAD/patterns/creational/pool.py |
Write docstrings for utility functions | from typing import Dict
class RegistryHolder(type):
REGISTRY: Dict[str, "RegistryHolder"] = {}
def __new__(cls, name, bases, attrs):
new_cls = type.__new__(cls, name, bases, attrs)
"""
Here the name of the class is used as key but it could be any class
parameter.
... | --- +++ @@ -19,12 +19,30 @@
class BaseRegisteredClass(metaclass=RegistryHolder):
+ """
+ Any class that will inherits from BaseRegisteredClass will be included
+ inside the dict RegistryHolder.REGISTRY, the key being the name of the
+ class and the associated value, the class itself.
+ """
def m... | https://raw.githubusercontent.com/faif/python-patterns/HEAD/patterns/behavioral/registry.py |
Generate helpful docstrings for debugging |
from __future__ import annotations
class ChatRoom:
def display_message(self, user: User, message: str) -> None:
return f"[{user} says]: {message}"
class User:
def __init__(self, name: str) -> None:
self.name = name
self.chat_room = ChatRoom()
def say(self, message: str) -> No... | --- +++ @@ -1,14 +1,25 @@+"""
+https://www.djangospin.com/design-patterns-python/mediator/
+
+Objects in a system communicate through a Mediator instead of directly with each other.
+This reduces the dependencies between communicating objects, thereby reducing coupling.
+
+*TL;DR
+Encapsulates how a set of objects inte... | https://raw.githubusercontent.com/faif/python-patterns/HEAD/patterns/behavioral/mediator.py |
Generate docstrings for script automation | from __future__ import annotations
import json
from collections.abc import AsyncGenerator
from typing import Any
from exo.shared.types.chunks import (
ErrorChunk,
PrefillProgressChunk,
TokenChunk,
ToolCallChunk,
)
from exo.shared.types.common import CommandId
from exo.shared.types.ollama_api import (
... | --- +++ @@ -67,6 +67,7 @@ def _get_usage(
chunk: TokenChunk | ToolCallChunk,
) -> tuple[int | None, int | None]:
+ """Extract (prompt_eval_count, eval_count) from a chunk."""
if chunk.usage is not None:
return (chunk.usage.prompt_tokens, chunk.usage.completion_tokens)
if chunk.stats is not N... | https://raw.githubusercontent.com/exo-explore/exo/HEAD/src/exo/master/adapters/ollama.py |
Add verbose docstrings with examples | import os
import shutil
import sys
import tomllib
from collections.abc import Sequence
from dataclasses import dataclass, field
from subprocess import CalledProcessError
from typing import Self, cast
import anyio
from anyio import fail_after, open_process, to_thread
from anyio.streams.buffered import BufferedByteRecei... | --- +++ @@ -44,6 +44,10 @@
async def _get_thunderbolt_devices() -> set[str] | None:
+ """Get Thunderbolt interface device names (e.g., en2, en3) from hardware ports.
+
+ Returns None if the networksetup command fails.
+ """
result = await anyio.run_process(
["networksetup", "-listallhardwarep... | https://raw.githubusercontent.com/exo-explore/exo/HEAD/src/exo/utils/info_gatherer/info_gatherer.py |
Document helper functions with docstrings | import base64
import contextlib
import json
import random
import time
from collections.abc import AsyncGenerator, Awaitable, Callable, Iterable
from datetime import datetime, timezone
from http import HTTPStatus
from pathlib import Path
from typing import Annotated, Literal, cast
from uuid import uuid4
import anyio
fr... | --- +++ @@ -186,6 +186,7 @@
def _ensure_seed(params: AdvancedImageParams | None) -> AdvancedImageParams:
+ """Ensure advanced params has a seed set for distributed consistency."""
if params is None:
return AdvancedImageParams(seed=random.randint(0, 2**32 - 1))
if params.seed is None:
@@ -570,6... | https://raw.githubusercontent.com/exo-explore/exo/HEAD/src/exo/master/api.py |
Improve documentation using docstrings | import base64
import io
import random
import tempfile
import time
from pathlib import Path
from typing import Generator, Literal
import mlx.core as mx
from PIL import Image
from exo.shared.types.api import (
AdvancedImageParams,
ImageEditsTaskParams,
ImageGenerationStats,
ImageGenerationTaskParams,
... | --- +++ @@ -25,6 +25,7 @@
def parse_size(size_str: ImageSize) -> tuple[int, int]:
+ """Parse size parameter like '1024x1024' to (width, height) tuple."""
if size_str == "auto":
return (1024, 1024)
@@ -43,6 +44,7 @@
def warmup_image_generator(model: DistributedImageModel) -> Image.Image | None... | https://raw.githubusercontent.com/exo-explore/exo/HEAD/src/exo/worker/engines/image/generate.py |
Document all endpoints with docstrings | import time
from typing import Generic, TypeVar
K = TypeVar("K")
class KeyedBackoff(Generic[K]):
def __init__(self, base: float = 0.5, cap: float = 10.0):
self._base = base
self._cap = cap
self._attempts: dict[K, int] = {}
self._last_time: dict[K, float] = {}
def should_proc... | --- +++ @@ -5,6 +5,7 @@
class KeyedBackoff(Generic[K]):
+ """Tracks exponential backoff state per key."""
def __init__(self, base: float = 0.5, cap: float = 10.0):
self._base = base
@@ -13,6 +14,7 @@ self._last_time: dict[K, float] = {}
def should_proceed(self, key: K) -> bool:
+ ... | https://raw.githubusercontent.com/exo-explore/exo/HEAD/src/exo/utils/keyed_backoff.py |
Add detailed documentation for each class |
import json
import re
from collections.abc import AsyncGenerator
from typing import Any
from exo.shared.types.api import FinishReason, Usage
from exo.shared.types.chunks import (
ErrorChunk,
PrefillProgressChunk,
TokenChunk,
ToolCallChunk,
)
from exo.shared.types.claude_api import (
ClaudeContentB... | --- +++ @@ -1,3 +1,4 @@+"""Claude Messages API adapter for converting requests/responses."""
import json
import re
@@ -41,6 +42,7 @@ def finish_reason_to_claude_stop_reason(
finish_reason: FinishReason | None,
) -> ClaudeStopReason | None:
+ """Map OpenAI finish_reason to Claude stop_reason."""
if fin... | https://raw.githubusercontent.com/exo-explore/exo/HEAD/src/exo/master/adapters/claude.py |
Add structured docstrings to improve clarity | from collections.abc import Mapping, Sequence
from datetime import datetime
from typing import Any, cast
from pydantic import ConfigDict, Field, field_serializer, field_validator
from pydantic.alias_generators import to_camel
from exo.shared.topology import Topology, TopologySnapshot
from exo.shared.types.common impo... | --- +++ @@ -25,6 +25,12 @@
class State(CamelCaseModel):
+ """Global system state.
+
+ The :class:`Topology` instance is encoded/decoded via an immutable
+ :class:`~shared.topology.TopologySnapshot` to ensure compatibility with
+ standard JSON serialisation.
+ """
model_config = ConfigDict(
... | https://raw.githubusercontent.com/exo-explore/exo/HEAD/src/exo/shared/types/state.py |
Add docstrings to improve code quality |
from typing import Any, Literal
from pydantic import BaseModel, Field
from exo.shared.types.common import ModelId
# Tool definition types
ClaudeToolInputSchema = dict[str, Any]
class ClaudeToolDefinition(BaseModel, frozen=True):
name: str
description: str | None = None
input_schema: ClaudeToolInputSc... | --- +++ @@ -1,3 +1,4 @@+"""Claude Messages API types for request/response conversion."""
from typing import Any, Literal
@@ -10,6 +11,7 @@
class ClaudeToolDefinition(BaseModel, frozen=True):
+ """Tool definition in Claude Messages API request."""
name: str
description: str | None = None
@@ -23,1... | https://raw.githubusercontent.com/exo-explore/exo/HEAD/src/exo/shared/types/claude_api.py |
Add detailed docstrings explaining each function | from math import ceil
from typing import Self, overload
from exo.utils.pydantic_ext import FrozenModel
class Memory(FrozenModel):
in_bytes: int = 0
@classmethod
def from_bytes(cls, val: int) -> Self:
return cls(in_bytes=val)
@property
def in_kb(self) -> int:
return ceil(self.in_... | --- +++ @@ -9,50 +9,62 @@
@classmethod
def from_bytes(cls, val: int) -> Self:
+ """Construct a new Memory object from a number of bytes"""
return cls(in_bytes=val)
@property
def in_kb(self) -> int:
+ """The approximate kilobytes this memory represents, rounded up. Setting t... | https://raw.githubusercontent.com/exo-explore/exo/HEAD/src/exo/shared/types/memory.py |
Add professional docstrings to my codebase | import shutil
from collections.abc import Sequence
from pathlib import Path
from typing import Literal, Self
import psutil
from exo.shared.types.memory import Memory
from exo.shared.types.thunderbolt import ThunderboltIdentifier
from exo.utils.pydantic_ext import CamelCaseModel
class MemoryUsage(CamelCaseModel):
... | --- +++ @@ -41,12 +41,14 @@
class DiskUsage(CamelCaseModel):
+ """Disk space usage for the models directory."""
total: Memory
available: Memory
@classmethod
def from_path(cls, path: Path) -> Self:
+ """Get disk usage stats for the partition containing path."""
total, _used... | https://raw.githubusercontent.com/exo-explore/exo/HEAD/src/exo/shared/types/profiling.py |
Write clean docstrings for readability | import contextlib
import os
import pathlib
import tempfile
from typing import LiteralString
type StrPath = str | os.PathLike[str]
type BytesPath = bytes | os.PathLike[bytes]
type StrOrBytesPath = str | bytes | os.PathLike[str] | os.PathLike[bytes]
def delete_if_exists(filename: StrOrBytesPath) -> None:
with cont... | --- +++ @@ -15,12 +15,18 @@
def ensure_parent_directory_exists(filename: StrPath) -> None:
+ """
+ Ensure the directory containing the file exists (create it if necessary).
+ """
pathlib.Path(filename).parent.mkdir(parents=True, exist_ok=True)
def ensure_directory_exists(dirname: StrPath) -> None... | https://raw.githubusercontent.com/exo-explore/exo/HEAD/src/exo/utils/fs.py |
Provide docstrings following PEP 257 | import asyncio
import hashlib
import os
import shutil
import ssl
import time
import traceback
from collections.abc import Awaitable
from datetime import timedelta
from pathlib import Path
from typing import Callable, Literal
from urllib.parse import urljoin
import aiofiles
import aiofiles.os as aios
import aiohttp
imp... | --- +++ @@ -45,9 +45,11 @@
class HuggingFaceAuthenticationError(Exception):
+ """Raised when HuggingFace returns 401/403 for a model download."""
class HuggingFaceRateLimitError(Exception):
+ """429 Huggingface code"""
async def _build_auth_error_message(status_code: int, model_id: ModelId) -> str:
... | https://raw.githubusercontent.com/exo-explore/exo/HEAD/src/exo/download/download_utils.py |
Generate consistent documentation across files | #!/usr/bin/env python3
from __future__ import annotations
import argparse
import json
import sys
import urllib.request
from concurrent.futures import ThreadPoolExecutor, as_completed
from pathlib import Path
import tomlkit
CARDS_DIR = (
Path(__file__).resolve().parent.parent / "resources" / "inference_model_car... | --- +++ @@ -1,4 +1,13 @@ #!/usr/bin/env python3
+"""Fetch num_key_value_heads from HuggingFace config.json and update TOML model cards.
+
+Usage:
+ # Update only cards missing num_key_value_heads
+ uv run python scripts/fetch_kv_heads.py --missing
+
+ # Update all cards (overwrite existing values)
+ uv run ... | https://raw.githubusercontent.com/exo-explore/exo/HEAD/scripts/fetch_kv_heads.py |
Write clean docstrings for readability | import logging
import sys
from collections.abc import Iterator
from pathlib import Path
import zstandard
from hypercorn import Config
from hypercorn.logging import Logger as HypercornLogger
from loguru import logger
_MAX_LOG_ARCHIVES = 5
def _zstd_compress(filepath: str) -> None:
source = Path(filepath)
des... | --- +++ @@ -44,6 +44,7 @@
def logger_setup(log_file: Path | None, verbosity: int = 0):
+ """Set up logging for this process - formatting, file handles, verbosity and output"""
logging.getLogger("exo_pyo3_bindings").setLevel(logging.WARNING)
logging.getLogger("httpx").setLevel(logging.WARNING)
@@ -85,... | https://raw.githubusercontent.com/exo-explore/exo/HEAD/src/exo/shared/logging.py |
Help me add docstrings to my project | from abc import ABC, abstractmethod
from pathlib import Path
from typing import TYPE_CHECKING, Any, Generic, TypeVar
import mlx.core as mx
from mflux.models.common.config.config import Config
from mflux.models.common.latent_creator.latent_creator import Img2Img, LatentCreator
from mflux.utils.image_util import ImageUt... | --- +++ @@ -49,28 +49,75 @@ def cond_image_grid(
self,
) -> tuple[int, int, int] | list[tuple[int, int, int]] | None:
+ """Conditioning image grid dimensions for edit mode.
+
+ Returns:
+ Grid dimensions (edit) or None (standard generation).
+ """
...
@p... | https://raw.githubusercontent.com/exo-explore/exo/HEAD/src/exo/worker/engines/image/models/base.py |
Create Google-style docstrings for my code |
from collections.abc import AsyncGenerator
from itertools import count
from typing import Any
from exo.shared.types.api import Usage
from exo.shared.types.chunks import (
ErrorChunk,
PrefillProgressChunk,
TokenChunk,
ToolCallChunk,
)
from exo.shared.types.common import CommandId
from exo.shared.types.... | --- +++ @@ -1,3 +1,4 @@+"""OpenAI Responses API adapter for converting requests/responses."""
from collections.abc import AsyncGenerator
from itertools import count
@@ -49,10 +50,12 @@
def _format_sse(event: ResponsesStreamEvent) -> str:
+ """Format a streaming event as an SSE message."""
return f"event... | https://raw.githubusercontent.com/exo-explore/exo/HEAD/src/exo/master/adapters/responses.py |
Document this script properly | from pathlib import Path
from typing import Any
import mlx.core as mx
from mflux.models.common.config import ModelConfig
from mflux.models.common.config.config import Config
from mflux.models.qwen.latent_creator.qwen_latent_creator import QwenLatentCreator
from mflux.models.qwen.model.qwen_text_encoder.qwen_prompt_enc... | --- +++ @@ -76,6 +76,18 @@ def get_batched_cfg_data(
self,
) -> tuple[mx.array, mx.array, mx.array | None, mx.array | None] | None:
+ """Batch positive and negative embeddings for CFG with batch_size=2.
+
+ Pads shorter sequence to max length using zeros for embeddings
+ and zeros... | https://raw.githubusercontent.com/exo-explore/exo/HEAD/src/exo/worker/engines/image/models/qwen/adapter.py |
Add docstrings with type hints explained | import contextlib
import json
from collections import OrderedDict
from collections.abc import Iterator
from datetime import datetime, timezone
from io import BufferedRandom, BufferedReader
from pathlib import Path
import msgspec
import zstandard
from loguru import logger
from pydantic import TypeAdapter
from exo.shar... | --- +++ @@ -39,6 +39,7 @@
def _skip_record(f: BufferedReader) -> bool:
+ """Skip one length-prefixed record. Returns False on EOF."""
header = f.read(_HEADER_SIZE)
if len(header) < _HEADER_SIZE:
return False
@@ -47,6 +48,7 @@
def _read_record(f: BufferedReader) -> Event | None:
+ """Rea... | https://raw.githubusercontent.com/exo-explore/exo/HEAD/src/exo/master/event_log.py |
Auto-generate documentation strings for this file | from copy import copy
from itertools import count
from math import inf
from os import PathLike
from pathlib import Path
from typing import cast
from anyio import (
BrokenResourceError,
ClosedResourceError,
move_on_after,
sleep_forever,
)
from exo_pyo3_bindings import (
AllQueuesFullError,
Keypa... | --- +++ @@ -74,6 +74,11 @@ self.receiver.close()
async def publish(self, item: T):
+ """
+ Publish item T on this topic to all senders.
+ NB: this sends to ALL receivers, potentially including receivers held by the object doing the sending.
+ You should handle your own output ... | https://raw.githubusercontent.com/exo-explore/exo/HEAD/src/exo/routing/router.py |
Help me comply with documentation standards | from abc import ABC, abstractmethod
from collections.abc import Awaitable
from copy import copy
from datetime import timedelta
from pathlib import Path
from typing import AsyncIterator, Callable
from exo.download.download_utils import RepoDownloadProgress
from exo.shared.models.model_cards import ModelCard, ModelId, M... | --- +++ @@ -20,6 +20,15 @@ async def ensure_shard(
self, shard: ShardMetadata, config_only: bool = False
) -> Path:
+ """
+ Ensures that the shard is downloaded.
+ Does not allow multiple overlapping downloads at once.
+ If you try to download a Shard which overlaps a Shard... | https://raw.githubusercontent.com/exo-explore/exo/HEAD/src/exo/download/shard_downloader.py |
Generate missing documentation strings | from enum import Enum
from typing import TypeAlias, final
from pydantic import Field
from exo.shared.models.model_cards import ModelCard
from exo.utils.pydantic_ext import TaggedModel
class Sharding(str, Enum):
Tensor = "Tensor"
Pipeline = "Pipeline"
class BaseShardMetadata(TaggedModel):
model_card: ... | --- +++ @@ -13,6 +13,10 @@
class BaseShardMetadata(TaggedModel):
+ """
+ Defines a specific shard of the model that is ready to be run on a device.
+ Replaces previous `Shard` object.
+ """
model_card: ModelCard
device_rank: int
@@ -50,10 +54,17 @@
@final
class PipelineShardMetadata(BaseS... | https://raw.githubusercontent.com/exo-explore/exo/HEAD/src/exo/shared/types/worker/shards.py |
Add docstrings to improve collaboration | import contextlib
from collections.abc import Mapping, Sequence
from dataclasses import dataclass, field
from typing import Iterable
import rustworkx as rx
from pydantic import BaseModel, ConfigDict
from exo.shared.types.common import NodeId
from exo.shared.types.profiling import (
InterfaceType,
NodeNetworkI... | --- +++ @@ -182,6 +182,7 @@ self._graph.remove_edge_from_index(conn_idx)
def get_cycles(self) -> list[Cycle]:
+ """Get simple cycles in the graph, including singleton cycles"""
cycle_idxs = rx.simple_cycles(self._graph)
cycles: list[Cycle] = []
@@ -245,6 +246,11 @@ ... | https://raw.githubusercontent.com/exo-explore/exo/HEAD/src/exo/shared/topology.py |
Add missing documentation to my Python functions | from datetime import datetime
from typing import final
from pydantic import Field
from exo.shared.topology import Connection
from exo.shared.types.chunks import GenerationChunk, InputImageChunk
from exo.shared.types.common import CommandId, Id, NodeId, SessionId, SystemId
from exo.shared.types.tasks import Task, Task... | --- +++ @@ -15,6 +15,9 @@
class EventId(Id):
+ """
+ Newtype around `ID`
+ """
class BaseEvent(TaggedModel):
@@ -148,12 +151,14 @@
class IndexedEvent(CamelCaseModel):
+ """An event indexed by the master, with a globally unique index"""
idx: int = Field(ge=0)
event: Event
class ... | https://raw.githubusercontent.com/exo-explore/exo/HEAD/src/exo/shared/types/events.py |
Add docstrings for utility scripts | from loguru import logger
class OrderedBuffer[T]:
def __init__(self):
self.store: dict[int, T] = {}
self.next_idx_to_release: int = 0
def ingest(self, idx: int, t: T):
logger.trace(f"Ingested event {t}")
if idx < self.next_idx_to_release:
return
if idx in ... | --- +++ @@ -2,12 +2,19 @@
class OrderedBuffer[T]:
+ """
+ A buffer that resequences events to ensure their ordering is preserved.
+ Currently this buffer doesn't raise any errors if an event is lost
+ This buffer is NOT thread safe, and is designed to only be polled from one
+ source at a time.
+ ... | https://raw.githubusercontent.com/exo-explore/exo/HEAD/src/exo/utils/event_buffer.py |
Generate consistent docstrings | #!/usr/bin/env python3
from __future__ import annotations
import math
import sys
from pathlib import Path
from PIL import Image, ImageDraw
# Retina dimensions (2× logical 800×400)
WIDTH = 1600
HEIGHT = 740
# Icon positions in logical coords → retina coords
# App icon at (200, 190), Applications at (600, 190)
APP_X... | --- +++ @@ -1,4 +1,15 @@ #!/usr/bin/env python3
+"""Generate the DMG background image with a centered drag-to-Applications arrow.
+
+The output is a 1600×740 retina PNG (2× for 800×400 logical window).
+Icons are positioned at (200, 190) and (600, 190) in logical coordinates;
+the arrow is drawn centered between them.
... | https://raw.githubusercontent.com/exo-explore/exo/HEAD/packaging/dmg/generate-background.py |
Auto-generate documentation strings for this file | from enum import Enum
from typing import Annotated, Any
import aiofiles
import aiofiles.os as aios
import tomlkit
from anyio import Path, open_file
from huggingface_hub import model_info
from loguru import logger
from pydantic import (
AliasChoices,
BaseModel,
Field,
PositiveInt,
ValidationError,
... | --- +++ @@ -126,6 +126,7 @@
@staticmethod
async def fetch_from_hf(model_id: ModelId) -> "ModelCard":
+ """Fetches storage size and number of layers for a Hugging Face model, returns Pydantic ModelMeta."""
# TODO: failure if files do not exist
config_data = await fetch_config_data(mod... | https://raw.githubusercontent.com/exo-explore/exo/HEAD/src/exo/shared/models/model_cards.py |
Add docstrings to clarify complex logic | from pathlib import Path
from typing import Any
import mlx.core as mx
from mflux.models.common.config.config import Config
from mflux.models.common.config.model_config import ModelConfig
from mflux.models.flux.latent_creator.flux_latent_creator import FluxLatentCreator
from mflux.models.flux.model.flux_text_encoder.pr... | --- +++ @@ -71,6 +71,7 @@ def get_cfg_branch_data(
self, positive: bool
) -> tuple[mx.array, mx.array | None, mx.array | None, mx.array | None]:
+ """Flux doesn't use CFG, but we return positive data for compatibility."""
return (self._prompt_embeds, None, self._pooled_prompt_embeds, N... | https://raw.githubusercontent.com/exo-explore/exo/HEAD/src/exo/worker/engines/image/models/flux/adapter.py |
Add docstrings to clarify complex logic | import os
from fnmatch import fnmatch
from pathlib import Path
from typing import Callable, Generator, Iterable
import aiofiles
import aiofiles.os as aios
from loguru import logger
from exo.shared.types.worker.shards import ShardMetadata
def filter_repo_objects[T](
items: Iterable[T],
*,
allow_patterns:... | --- +++ @@ -63,10 +63,12 @@
def get_hf_home() -> Path:
+ """Get the Hugging Face home directory."""
return Path(os.environ.get("HF_HOME", Path.home() / ".cache" / "huggingface"))
async def get_hf_token() -> str | None:
+ """Retrieve the Hugging Face token from HF_TOKEN env var or HF_HOME directory."... | https://raw.githubusercontent.com/exo-explore/exo/HEAD/src/exo/download/huggingface_utils.py |
Add detailed documentation for each class |
from typing import Any, Literal
from pydantic import BaseModel
from exo.shared.types.common import ModelId
MessageRole = Literal["user", "assistant", "system", "developer"]
ReasoningEffort = Literal["none", "minimal", "low", "medium", "high", "xhigh"]
def resolve_reasoning_params(
reasoning_effort: ReasoningE... | --- +++ @@ -1,3 +1,8 @@+"""Canonical internal type for text generation task parameters.
+
+All external API formats (Chat Completions, Claude Messages, OpenAI Responses)
+are converted to TextGenerationTaskParams at the API boundary via adapters.
+"""
from typing import Any, Literal
@@ -13,6 +18,12 @@ reasonin... | https://raw.githubusercontent.com/exo-explore/exo/HEAD/src/exo/shared/types/text_generation.py |
Write documentation strings for class attributes |
import time
from typing import Any, Literal
from pydantic import BaseModel, Field
from exo.shared.types.common import ModelId
from exo.shared.types.text_generation import ReasoningEffort
# Type aliases
ResponseStatus = Literal["completed", "failed", "in_progress", "incomplete"]
ResponseRole = Literal["user", "assis... | --- +++ @@ -1,3 +1,10 @@+"""OpenAI Responses API wire types.
+
+These types model the OpenAI Responses API request/response format.
+ResponsesRequest is the API-level wire type; for the canonical internal
+task params type used by the inference pipeline, see
+``exo.shared.types.text_generation.TextGenerationTaskParams`... | https://raw.githubusercontent.com/exo-explore/exo/HEAD/src/exo/shared/types/openai_responses.py |
Add docstrings to improve readability | # pyright: reportAny=false, reportUnknownMemberType=false, reportUnknownVariableType=false, reportUnknownArgumentType=false
from __future__ import annotations
import argparse
import contextlib
import json
import os
import sys
import time
import tomllib
from dataclasses import dataclass, field
from pathlib import Path
... | --- +++ @@ -139,6 +139,7 @@
def validate_args(args_str: str, required_keys: list[str]) -> tuple[bool, str | None]:
+ """Parse JSON arguments and check required keys exist."""
try:
args = json.loads(args_str)
except (json.JSONDecodeError, TypeError) as exc:
@@ -156,6 +157,7 @@ array_key: st... | https://raw.githubusercontent.com/exo-explore/exo/HEAD/bench/eval_tool_calls.py |
Improve documentation using docstrings | import time
from collections.abc import Generator
from typing import Annotated, Any, Literal, get_args
from uuid import uuid4
from pydantic import BaseModel, Field, field_validator
from exo.shared.models.model_cards import ModelCard, ModelId
from exo.shared.types.common import CommandId, NodeId
from exo.shared.types.... | --- +++ @@ -299,6 +299,7 @@
def normalize_image_size(v: object) -> ImageSize:
+ """Shared validator for ImageSize fields: maps None → "auto" and rejects invalid values."""
if v is None:
return "auto"
if v not in get_args(ImageSize):
@@ -344,6 +345,7 @@
class ImageEditsTaskParams(BaseModel)... | https://raw.githubusercontent.com/exo-explore/exo/HEAD/src/exo/shared/types/api.py |
Write docstrings for algorithm functions | from collections.abc import Generator, Mapping
from loguru import logger
from exo.shared.models.model_cards import ModelCard
from exo.shared.topology import Topology
from exo.shared.types.common import Host, NodeId
from exo.shared.types.memory import Memory
from exo.shared.types.profiling import MemoryUsage, NodeNetw... | --- +++ @@ -127,6 +127,7 @@ cycle: Cycle,
node_memory: Mapping[NodeId, MemoryUsage],
) -> ShardAssignments:
+ """Create shard assignments for pipeline parallel execution."""
world_size = len(cycle)
use_cfg_parallel = model_card.uses_cfg and world_size >= 2 and world_size % 2 == 0
@@ -141,6 +142... | https://raw.githubusercontent.com/exo-explore/exo/HEAD/src/exo/master/placement_utils.py |
Add docstrings to make code maintainable | from collections import defaultdict
from collections.abc import AsyncGenerator, Mapping
import anyio
import httpx
from anyio import create_task_group
from loguru import logger
from exo.shared.topology import Topology
from exo.shared.types.common import NodeId
from exo.shared.types.profiling import NodeNetworkInfo
fro... | --- +++ @@ -20,6 +20,7 @@ out: dict[NodeId, set[str]],
client: httpx.AsyncClient,
) -> None:
+ """Check if a node is reachable at the given IP and verify its identity."""
if ":" in target_ip:
# TODO: use real IpAddress types
url = f"http://[{target_ip}]:52415/node_id"
@@ -82,6 +83,7 ... | https://raw.githubusercontent.com/exo-explore/exo/HEAD/src/exo/utils/info_gatherer/net_profile.py |
Generate helpful docstrings for debugging | import math
from pathlib import Path
from typing import Any, final
import mlx.core as mx
from mflux.models.common.config.config import Config
from mflux.models.common.config.model_config import ModelConfig
from mflux.models.flux.latent_creator.flux_latent_creator import FluxLatentCreator
from mflux.models.flux.model.f... | --- +++ @@ -29,6 +29,11 @@
@final
class FluxKontextPromptData(PromptData):
+ """Prompt data for FLUX.1-Kontext image editing.
+
+ Stores text embeddings along with conditioning latents and position IDs
+ for the input image.
+ """
def __init__(
self,
@@ -69,15 +74,18 @@
@property
... | https://raw.githubusercontent.com/exo-explore/exo/HEAD/src/exo/worker/engines/image/models/flux/kontext_adapter.py |
Generate docstrings for script automation | # type: ignore
#!/usr/bin/env python3
from __future__ import annotations
import argparse
import asyncio
import contextlib
import json
import multiprocessing
import random
import re
import sys
import time
import tomllib
from dataclasses import dataclass
from pathlib import Path
from typing import Any
import httpx
fro... | --- +++ @@ -1,5 +1,29 @@ # type: ignore
#!/usr/bin/env python3
+"""Quality evaluation for exo — matches Artificial Analysis methodology.
+
+Runs LLM benchmarks against exo's OpenAI-compatible API using the same
+prompts, temperature settings, and answer extraction as Artificial Analysis.
+
+Supported benchmarks:
+ gp... | https://raw.githubusercontent.com/exo-explore/exo/HEAD/bench/exo_eval.py |
Help me add docstrings to my project | from typing import Self
from pydantic import BaseModel
from exo.shared.types.profiling import MemoryUsage, SystemPerformanceProfile
from exo.utils.pydantic_ext import TaggedModel
class _TempMetrics(BaseModel, extra="ignore"):
cpu_temp_avg: float
gpu_temp_avg: float
class _MemoryMetrics(BaseModel, extra="... | --- +++ @@ -7,12 +7,14 @@
class _TempMetrics(BaseModel, extra="ignore"):
+ """Temperature-related metrics returned by macmon."""
cpu_temp_avg: float
gpu_temp_avg: float
class _MemoryMetrics(BaseModel, extra="ignore"):
+ """Memory-related metrics returned by macmon."""
ram_total: int
... | https://raw.githubusercontent.com/exo-explore/exo/HEAD/src/exo/utils/info_gatherer/macmon.py |
Document this script properly | # type: ignore
#!/usr/bin/env python3
from __future__ import annotations
import argparse
import contextlib
import itertools
import json
import sys
import time
from collections.abc import Callable
from concurrent.futures import ThreadPoolExecutor, as_completed
from pathlib import Path
from statistics import mean
from ... | --- +++ @@ -1,5 +1,19 @@ # type: ignore
#!/usr/bin/env python3
+"""Tool-calling eval for exo's OpenAI-compatible API.
+
+Tests whether models correctly:
+- Trigger tool calls when appropriate
+- Return valid JSON arguments matching function schemas
+- Handle multi-turn tool use (call -> result -> final answer)
+- Avoi... | https://raw.githubusercontent.com/exo-explore/exo/HEAD/bench/exo_bench.py |
Generate docstrings for script automation | from pathlib import Path
from typing import Any, Callable
from exo.worker.engines.image.config import ImageModelConfig
from exo.worker.engines.image.models.base import ModelAdapter
from exo.worker.engines.image.models.flux import (
FLUX_DEV_CONFIG,
FLUX_KONTEXT_CONFIG,
FLUX_SCHNELL_CONFIG,
FluxKontextM... | --- +++ @@ -46,6 +46,17 @@
def get_config_for_model(model_id: str) -> ImageModelConfig:
+ """Get configuration for a model ID.
+
+ Args:
+ model_id: The model identifier (e.g., "black-forest-labs/FLUX.1-schnell")
+
+ Returns:
+ The model configuration
+
+ Raises:
+ ValueError: If no... | https://raw.githubusercontent.com/exo-explore/exo/HEAD/src/exo/worker/engines/image/models/__init__.py |
Create structured documentation for my script | import math
from dataclasses import dataclass
from pathlib import Path
from typing import Any
import mlx.core as mx
from mflux.models.common.config.config import Config
from mflux.models.qwen.latent_creator.qwen_latent_creator import QwenLatentCreator
from mflux.models.qwen.model.qwen_transformer.qwen_transformer impo... | --- +++ @@ -96,6 +96,20 @@ def get_batched_cfg_data(
self,
) -> tuple[mx.array, mx.array, mx.array | None, mx.array | None] | None:
+ """Batch positive and negative embeddings for CFG with batch_size=2.
+
+ Pads shorter sequence to max length using zeros for embeddings
+ and zeros... | https://raw.githubusercontent.com/exo-explore/exo/HEAD/src/exo/worker/engines/image/models/qwen/edit_adapter.py |
Create documentation strings for testing functions | import platform
import socket
import sys
from subprocess import CalledProcessError
import psutil
from anyio import run_process
from exo.shared.types.profiling import InterfaceType, NetworkInterfaceInfo
def get_os_version() -> str:
if sys.platform == "darwin":
version = platform.mac_ver()[0]
retu... | --- +++ @@ -10,6 +10,11 @@
def get_os_version() -> str:
+ """Return the OS version string for this node.
+
+ On macOS this is the macOS version (e.g. ``"15.3"``).
+ On other platforms it falls back to the platform name (e.g. ``"Linux"``).
+ """
if sys.platform == "darwin":
version = platfo... | https://raw.githubusercontent.com/exo-explore/exo/HEAD/src/exo/utils/info_gatherer/system_info.py |
Add docstrings to meet PEP guidelines | import contextlib
import multiprocessing as mp
from dataclasses import dataclass, field
from math import inf
from multiprocessing.synchronize import Event
from queue import Empty, Full
from types import TracebackType
from typing import Any, Self
from anyio import (
CapacityLimiter,
ClosedResourceError,
End... | --- +++ @@ -32,6 +32,7 @@ return Sender(_state=self._state)
def clone_receiver(self) -> "Receiver[T]":
+ """Constructs a Receiver using a Senders shared state - similar to calling Receiver.clone() without needing the receiver"""
if self._closed:
raise ClosedResourceError
... | https://raw.githubusercontent.com/exo-explore/exo/HEAD/src/exo/utils/channels.py |
Create docstrings for API functions |
import time
from collections.abc import AsyncGenerator
from typing import Any
from exo.shared.types.api import (
ChatCompletionChoice,
ChatCompletionMessage,
ChatCompletionMessageText,
ChatCompletionRequest,
ChatCompletionResponse,
ErrorInfo,
ErrorResponse,
FinishReason,
Logprobs,
... | --- +++ @@ -1,3 +1,4 @@+"""OpenAI Chat Completions API adapter for converting requests/responses."""
import time
from collections.abc import AsyncGenerator
@@ -112,6 +113,7 @@ def chunk_to_response(
chunk: TokenChunk, command_id: CommandId
) -> ChatCompletionResponse:
+ """Convert a TokenChunk to a streami... | https://raw.githubusercontent.com/exo-explore/exo/HEAD/src/exo/master/adapters/chat_completions.py |
Add inline docstrings for readability | import mlx.core as mx
class ImagePatchKVCache:
def __init__(
self,
batch_size: int,
num_heads: int,
image_seq_len: int,
head_dim: int,
dtype: mx.Dtype = mx.float32,
):
self.batch_size = batch_size
self.num_heads = num_heads
self.image_se... | --- +++ @@ -2,6 +2,12 @@
class ImagePatchKVCache:
+ """KV cache that stores only IMAGE K/V with patch-level updates.
+
+ Only caches image K/V since:
+ - Text K/V is always computed fresh (same for all patches)
+ - Only image portion needs stale/fresh cache management across patches
+ """
def ... | https://raw.githubusercontent.com/exo-explore/exo/HEAD/src/exo/worker/engines/image/pipeline/kv_cache.py |
Write docstrings describing each step | from collections.abc import Iterator
from dataclasses import dataclass
from math import ceil
from typing import Any, Optional, final
import mlx.core as mx
from mflux.models.common.config.config import Config
from mflux.utils.exceptions import StopImageGenerationException
from tqdm import tqdm
from exo.shared.constant... | --- +++ @@ -70,6 +70,12 @@
class DiffusionRunner:
+ """Orchestrates the diffusion loop for image generation.
+
+ In distributed mode, it implements PipeFusion with:
+ - Sync pipeline for initial timesteps (full image, all devices in lockstep)
+ - Async pipeline for later timesteps (patches processed ind... | https://raw.githubusercontent.com/exo-explore/exo/HEAD/src/exo/worker/engines/image/pipeline/runner.py |
Write documentation strings for class attributes | from abc import ABC, abstractmethod
from enum import Enum
from typing import Generic, Self, TypeVar
import mlx.core as mx
from exo.worker.engines.image.models.base import RotaryEmbeddings
from exo.worker.engines.image.pipeline.kv_cache import ImagePatchKVCache
BlockT = TypeVar("BlockT")
class BlockWrapperMode(Enum... | --- +++ @@ -16,6 +16,13 @@
class BlockWrapperMixin:
+ """Common cache management logic for block wrappers.
+
+ Including:
+ - KV cache creation and management
+ - Mode
+ - Patch range setting
+ """
_text_seq_len: int
_kv_cache: ImagePatchKVCache | None
@@ -36,6 +43,16 @@ patch_... | https://raw.githubusercontent.com/exo-explore/exo/HEAD/src/exo/worker/engines/image/pipeline/block_wrapper.py |
Help me document legacy Python code | import functools
import math
import time
from copy import deepcopy
from typing import Callable, Generator, cast, get_args
import mlx.core as mx
from mlx_lm.generate import (
maybe_quantize_kv_cache,
stream_generate,
)
from mlx_lm.models.cache import ArraysCache, RotatingKVCache
from mlx_lm.sample_utils import ... | --- +++ @@ -63,6 +63,7 @@
class PrefillCancelled(BaseException):
+ """Raised when prefill is cancelled via the progress callback."""
def _has_pipeline_communication_layer(model: Model):
@@ -83,6 +84,26 @@ distributed_prompt_progress_callback: Callable[[], None] | None,
group: mx.distributed.Group,
... | https://raw.githubusercontent.com/exo-explore/exo/HEAD/src/exo/worker/engines/mlx/generator/generate.py |
Write reusable docstrings | import os
from copy import deepcopy
import mlx.core as mx
import psutil
from mlx_lm.models.cache import (
ArraysCache,
CacheList,
KVCache,
QuantizedKVCache,
RotatingKVCache,
)
from mlx_lm.tokenizer_utils import TokenizerWrapper
from exo.shared.types.memory import Memory
from exo.shared.types.mlx i... | --- +++ @@ -37,6 +37,7 @@
class CacheSnapshot:
+ """Snapshot of states at a known token position."""
def __init__(
self, states: list[RotatingKVCache | ArraysCache | None], token_count: int
@@ -70,6 +71,7 @@
def has_non_kv_caches(cache: KVCacheType) -> bool:
+ """Check if a cache contains ... | https://raw.githubusercontent.com/exo-explore/exo/HEAD/src/exo/worker/engines/mlx/cache.py |
Generate docstrings for this script | import json
import os
import re
import sys
import tempfile
import time
from pathlib import Path
from typing import Any, cast
# Monkey-patch for transformers 5.x compatibility
# Kimi's tokenization_kimi.py imports bytes_to_unicode from the old location
# which was moved in transformers 5.0.0rc2
try:
import transfor... | --- +++ @@ -94,6 +94,9 @@ def mlx_distributed_init(
bound_instance: BoundInstance,
) -> Group:
+ """
+ Initialize MLX distributed.
+ """
rank = bound_instance.bound_shard.device_rank
logger.info(f"Starting initialization for rank {rank}")
@@ -283,6 +286,7 @@
def get_tokenizer(model_path: ... | https://raw.githubusercontent.com/exo-explore/exo/HEAD/src/exo/worker/engines/mlx/utils_mlx.py |
Add detailed docstrings explaining each function | import base64
import time
from typing import TYPE_CHECKING, Literal
import mlx.core as mx
from exo.shared.constants import EXO_MAX_CHUNK_SIZE, EXO_TRACING_ENABLED
from exo.shared.models.model_cards import ModelTask
from exo.shared.tracing import clear_trace_buffer, get_trace_buffer
from exo.shared.types.api import Im... | --- +++ @@ -69,6 +69,11 @@
def _is_primary_output_node(shard_metadata: ShardMetadata) -> bool:
+ """Check if this node is the primary output node for image generation.
+
+ For CFG models: the last pipeline stage in CFG group 0 (positive prompt).
+ For non-CFG models: the last pipeline stage.
+ """
... | https://raw.githubusercontent.com/exo-explore/exo/HEAD/src/exo/worker/runner/image_models/runner.py |
Create documentation strings for testing functions | import os
import threading
from abc import ABC, abstractmethod
from collections.abc import Callable
from functools import partial
from inspect import signature
from typing import TYPE_CHECKING, Any, Literal, Protocol, cast
import mlx.core as mx
import mlx.nn as nn
from mlx.nn.layers.distributed import (
shard_inpl... | --- +++ @@ -87,6 +87,11 @@ timeout_seconds: float = 60.0,
on_timeout: TimeoutCallback | None = None,
) -> None:
+ """Evaluate MLX item with a hard timeout.
+
+ If on_timeout callback is provided, it will be called before terminating
+ the process. This allows the runner to send a failure event before... | https://raw.githubusercontent.com/exo-explore/exo/HEAD/src/exo/worker/engines/mlx/auto_parallel.py |
Provide docstrings following PEP 257 | import itertools
import time
from abc import ABC, abstractmethod
from collections import deque
from collections.abc import Generator, Iterable
from dataclasses import dataclass, field
import mlx.core as mx
from mlx_lm.tokenizer_utils import TokenizerWrapper
from exo.shared.constants import EXO_MAX_CONCURRENT_REQUESTS... | --- +++ @@ -93,6 +93,7 @@
def _check_for_debug_prompts(task_params: TextGenerationTaskParams) -> None:
+ """Check for debug prompt triggers in the input."""
from exo.worker.engines.mlx.utils_mlx import mlx_force_oom
if len(task_params.input) == 0:
@@ -156,11 +157,13 @@ self._maybe_queue.appen... | https://raw.githubusercontent.com/exo-explore/exo/HEAD/src/exo/worker/runner/llm_inference/batch_generator.py |
Write docstrings for utility functions | from collections.abc import Generator
from functools import cache
from typing import Any
from mlx_lm.models.deepseek_v32 import Model as DeepseekV32Model
from mlx_lm.models.gpt_oss import Model as GptOssModel
from mlx_lm.tokenizer_utils import TokenizerWrapper
from openai_harmony import ( # pyright: ignore[reportMiss... | --- +++ @@ -137,6 +137,12 @@ def parse_deepseek_v32(
responses: Generator[GenerationResponse | None],
) -> Generator[GenerationResponse | ToolCallResponse | None]:
+ """Parse DeepSeek V3.2 DSML tool calls from the generation stream.
+
+ Uses accumulated-text matching (not per-token marker checks) because
+ ... | https://raw.githubusercontent.com/exo-explore/exo/HEAD/src/exo/worker/runner/llm_inference/model_output_parsers.py |
Write reusable docstrings | #!/usr/bin/env python3
from __future__ import annotations
import argparse
import re
import shutil
import sys
from pathlib import Path
from typing import TYPE_CHECKING
if TYPE_CHECKING:
from mflux.models.flux.variants.txt2img.flux import Flux1
HF_ORG = "exolabs"
def get_model_class(model_name: str) -> type:
... | --- +++ @@ -1,4 +1,18 @@ #!/usr/bin/env python3
+"""
+Download an mflux model, quantize it, and upload to HuggingFace.
+
+Usage (run from mflux project directory):
+ cd /path/to/mflux
+ uv run python /path/to/quantize_and_upload.py --model black-forest-labs/FLUX.1-Kontext-dev
+ uv run python /path/to/quantize_... | https://raw.githubusercontent.com/exo-explore/exo/HEAD/tmp/quantize_and_upload.py |
Add docstrings to my Python code |
import os
from typing import List, Optional, Dict, Any
from pathlib import Path
import hashlib
from datetime import datetime, timedelta
from agent.memory.config import MemoryConfig, get_default_memory_config
from agent.memory.storage import MemoryStorage, MemoryChunk, SearchResult
from agent.memory.chunker import Tex... | --- +++ @@ -1,3 +1,8 @@+"""
+Memory manager for AgentMesh
+
+Provides high-level interface for memory operations
+"""
import os
from typing import List, Optional, Dict, Any
@@ -13,6 +18,11 @@
class MemoryManager:
+ """
+ Memory manager with hybrid search capabilities
+
+ Provides long-term memory f... | https://raw.githubusercontent.com/zhayujie/chatgpt-on-wechat/HEAD/agent/memory/manager.py |
Generate descriptive docstrings automatically |
import threading
from typing import Optional, Callable, Any, List, Dict
from pathlib import Path
from datetime import datetime
from common.log import logger
SUMMARIZE_SYSTEM_PROMPT = """你是一个记忆提取助手。你的任务是从对话记录中提取值得记住的信息,生成简洁的记忆摘要。
输出要求:
1. 以事件/关键信息为维度记录,每条一行,用 "- " 开头
2. 记录有价值的关键信息,例如用户提出的要求及助手的解决方案,对话中涉及的事实信息,用户的偏好、... | --- +++ @@ -1,3 +1,13 @@+"""
+Memory flush manager
+
+Handles memory persistence when conversation context is trimmed or overflows:
+- Uses LLM to summarize discarded messages into concise key-information entries
+- Writes to daily memory files (lazy creation)
+- Deduplicates trim flushes to avoid repeated writes
+- Ru... | https://raw.githubusercontent.com/zhayujie/chatgpt-on-wechat/HEAD/agent/memory/summarizer.py |
Document classes and their methods |
from typing import Dict, Any, Optional
from agent.tools.base_tool import BaseTool
class MemorySearchTool(BaseTool):
name: str = "memory_search"
description: str = (
"Search agent's long-term memory using semantic and keyword search. "
"Use this to recall past conversations, preferences, ... | --- +++ @@ -1,9 +1,15 @@+"""
+Memory search tool
+
+Allows agents to search their memory using semantic and keyword search
+"""
from typing import Dict, Any, Optional
from agent.tools.base_tool import BaseTool
class MemorySearchTool(BaseTool):
+ """Tool for searching agent memory"""
name: str = "... | https://raw.githubusercontent.com/zhayujie/chatgpt-on-wechat/HEAD/agent/tools/memory/memory_search.py |
Write docstrings that follow conventions |
import time
from typing import Callable, Optional
from common.log import logger
class ChatService:
def __init__(self, agent_bridge):
self.agent_bridge = agent_bridge
def run(self, query: str, session_id: str, send_chunk_fn: Callable[[dict], None],
channel_type: str = ""):
agent... | --- +++ @@ -1,3 +1,9 @@+"""
+ChatService - Wraps the Agent stream execution to produce CHAT protocol chunks.
+
+Translates agent events (message_update, message_end, tool_execution_end, etc.)
+into the CHAT socket protocol format (content chunks with segment_id, tool_calls chunks).
+"""
import time
from typing impo... | https://raw.githubusercontent.com/zhayujie/chatgpt-on-wechat/HEAD/agent/chat/service.py |
Write beginner-friendly docstrings |
import os
import re
import uuid
from typing import Dict, Any, Optional, Set
from urllib.parse import urlparse, unquote
import requests
from agent.tools.base_tool import BaseTool, ToolResult
from agent.tools.utils.truncate import truncate_head, format_size
from common.log import logger
DEFAULT_TIMEOUT = 30
MAX_FILE... | --- +++ @@ -1,3 +1,10 @@+"""
+Web Fetch tool - Fetch and extract readable content from web pages and remote files.
+
+Supports:
+- HTML web pages: extracts readable text content
+- Document files (PDF, Word, TXT, Markdown, etc.): downloads to workspace/tmp and parses content
+"""
import os
import re
@@ -38,11 +45,1... | https://raw.githubusercontent.com/zhayujie/chatgpt-on-wechat/HEAD/agent/tools/web_fetch/web_fetch.py |
Write beginner-friendly docstrings |
import os
from typing import Optional, List
from agent.protocol import Agent, LLMModel, LLMRequest
from bridge.agent_event_handler import AgentEventHandler
from bridge.agent_initializer import AgentInitializer
from bridge.bridge import Bridge
from bridge.context import Context
from bridge.reply import Reply, ReplyTyp... | --- +++ @@ -1,3 +1,6 @@+"""
+Agent Bridge - Integrates Agent system with existing COW bridge
+"""
import os
from typing import Optional, List
@@ -15,6 +18,14 @@
def add_openai_compatible_support(bot_instance):
+ """
+ Dynamically add OpenAI-compatible tool calling support to a bot instance.
+
+ Thi... | https://raw.githubusercontent.com/zhayujie/chatgpt-on-wechat/HEAD/bridge/agent_bridge.py |
Write docstrings for data processing functions |
from __future__ import annotations
from typing import List, Tuple
from dataclasses import dataclass
@dataclass
class TextChunk:
text: str
start_line: int
end_line: int
class TextChunker:
def __init__(self, max_tokens: int = 500, overlap_tokens: int = 50):
self.max_tokens = max_tokens
... | --- +++ @@ -1,3 +1,8 @@+"""
+Text chunking utilities for memory
+
+Splits text into chunks with token limits and overlap
+"""
from __future__ import annotations
from typing import List, Tuple
@@ -6,20 +11,38 @@
@dataclass
class TextChunk:
+ """Represents a text chunk with line numbers"""
text: str
s... | https://raw.githubusercontent.com/zhayujie/chatgpt-on-wechat/HEAD/agent/memory/chunker.py |
Help me document legacy Python code | import time
import json
import logging
import mimetypes
import os
import threading
import time
import uuid
from queue import Queue, Empty
import web
from bridge.context import *
from bridge.reply import Reply, ReplyType
from channel.chat_channel import ChatChannel, check_prefix
from channel.chat_message import ChatMe... | --- +++ @@ -69,10 +69,12 @@ self._http_server = None
def _generate_msg_id(self):
+ """生成唯一的消息ID"""
self.msg_id_counter += 1
return str(int(time.time())) + str(self.msg_id_counter)
def _generate_request_id(self):
+ """生成唯一的请求ID"""
return str(uuid.uuid4())
... | https://raw.githubusercontent.com/zhayujie/chatgpt-on-wechat/HEAD/channel/web/web_channel.py |
Write docstrings for algorithm functions |
from __future__ import annotations
from typing import Dict, List, Optional, Any
from dataclasses import dataclass, field
@dataclass
class SkillInstallSpec:
kind: str # brew, pip, npm, download, etc.
id: Optional[str] = None
label: Optional[str] = None
bins: List[str] = field(default_factory=list)
... | --- +++ @@ -1,3 +1,6 @@+"""
+Type definitions for skills system.
+"""
from __future__ import annotations
from typing import Dict, List, Optional, Any
@@ -6,6 +9,7 @@
@dataclass
class SkillInstallSpec:
+ """Specification for installing skill dependencies."""
kind: str # brew, pip, npm, download, etc.
... | https://raw.githubusercontent.com/zhayujie/chatgpt-on-wechat/HEAD/agent/skills/types.py |
Document this script properly |
from __future__ import annotations
import json
import sqlite3
import threading
import time
from pathlib import Path
from typing import Any, Dict, List, Optional
from common.log import logger
# ---------------------------------------------------------------------------
# Schema
# -----------------------------------... | --- +++ @@ -1,3 +1,14 @@+"""
+Conversation history persistence using SQLite.
+
+Design:
+- sessions table: per-session metadata (channel_type, last_active, msg_count)
+- messages table: individual messages stored as JSON, append-only
+- Pruning: age-based only (sessions not updated within N days are deleted)
+- Thread-... | https://raw.githubusercontent.com/zhayujie/chatgpt-on-wechat/HEAD/agent/memory/conversation_store.py |
Replace inline comments with docstrings |
import os
from typing import Optional
from config import conf
from common.log import logger
from common.utils import expand_path
from bridge.context import Context, ContextType
from bridge.reply import Reply, ReplyType
# Global scheduler service instance
_scheduler_service = None
_task_store = None
def init_schedul... | --- +++ @@ -1,3 +1,6 @@+"""
+Integration module for scheduler with AgentBridge
+"""
import os
from typing import Optional
@@ -13,6 +16,15 @@
def init_scheduler(agent_bridge) -> bool:
+ """
+ Initialize scheduler service
+
+ Args:
+ agent_bridge: AgentBridge instance
+
+ Returns:
+... | https://raw.githubusercontent.com/zhayujie/chatgpt-on-wechat/HEAD/agent/tools/scheduler/integration.py |
Write Python docstrings for this snippet |
from typing import List
from agent.skills.types import Skill, SkillEntry
def format_skills_for_prompt(skills: List[Skill]) -> str:
# Filter out skills that should not be invoked by the model
visible_skills = [s for s in skills if not s.disable_model_invocation]
if not visible_skills:
return ... | --- +++ @@ -1,9 +1,21 @@+"""
+Skill formatter for generating prompts from skills.
+"""
from typing import List
from agent.skills.types import Skill, SkillEntry
def format_skills_for_prompt(skills: List[Skill]) -> str:
+ """
+ Format skills for inclusion in a system prompt.
+
+ Uses XML format per ... | https://raw.githubusercontent.com/zhayujie/chatgpt-on-wechat/HEAD/agent/skills/formatter.py |
Add docstrings to meet PEP guidelines |
import os
from typing import Dict, Any
from agent.tools.base_tool import BaseTool, ToolResult
from common.utils import expand_path
from agent.tools.utils.diff import (
strip_bom,
detect_line_ending,
normalize_to_lf,
restore_line_endings,
normalize_for_fuzzy_match,
fuzzy_find_text,
generate... | --- +++ @@ -1,3 +1,7 @@+"""
+Edit tool - Precise file editing
+Edit files through exact text replacement
+"""
import os
from typing import Dict, Any
@@ -16,6 +20,7 @@
class Edit(BaseTool):
+ """Tool for precise file editing"""
name: str = "edit"
description: str = "Edit a file by replacing ex... | https://raw.githubusercontent.com/zhayujie/chatgpt-on-wechat/HEAD/agent/tools/edit/edit.py |
Write clean docstrings for readability | from __future__ import annotations
import time
import uuid
from dataclasses import dataclass, field
from enum import Enum
from typing import Dict, Any, List
class TaskType(Enum):
TEXT = "text"
IMAGE = "image"
VIDEO = "video"
AUDIO = "audio"
FILE = "file"
MIXED = "mixed"
class TaskStatus(Enum... | --- +++ @@ -7,6 +7,7 @@
class TaskType(Enum):
+ """Enum representing different types of tasks."""
TEXT = "text"
IMAGE = "image"
VIDEO = "video"
@@ -16,6 +17,7 @@
class TaskStatus(Enum):
+ """Enum representing the status of a task."""
INIT = "init" # Initial state
PROCESSING = "pr... | https://raw.githubusercontent.com/zhayujie/chatgpt-on-wechat/HEAD/agent/protocol/task.py |
Add docstrings explaining edge cases |
import os
import re
import sys
import subprocess
import tempfile
from typing import Dict, Any
from agent.tools.base_tool import BaseTool, ToolResult
from agent.tools.utils.truncate import truncate_tail, format_size, DEFAULT_MAX_LINES, DEFAULT_MAX_BYTES
from common.log import logger
from common.utils import expand_pat... | --- +++ @@ -1,3 +1,6 @@+"""
+Bash tool - Execute bash commands
+"""
import os
import re
@@ -13,6 +16,7 @@
class Bash(BaseTool):
+ """Tool for executing bash commands"""
name: str = "bash"
description: str = f"""Execute a bash command in the current working directory. Returns stdout and stderr. Ou... | https://raw.githubusercontent.com/zhayujie/chatgpt-on-wechat/HEAD/agent/tools/bash/bash.py |
Add docstrings including usage examples |
from __future__ import annotations
import os
from typing import List, Optional, Dict
from dataclasses import dataclass
from common.log import logger
from .builder import ContextFile
# 默认文件名常量
DEFAULT_AGENT_FILENAME = "AGENT.md"
DEFAULT_USER_FILENAME = "USER.md"
DEFAULT_RULE_FILENAME = "RULE.md"
DEFAULT_MEMORY_FILEN... | --- +++ @@ -1,3 +1,8 @@+"""
+Workspace Management - 工作空间管理模块
+
+负责初始化工作空间、创建模板文件、加载上下文文件
+"""
from __future__ import annotations
import os
@@ -18,6 +23,7 @@
@dataclass
class WorkspaceFiles:
+ """工作空间文件路径"""
agent_path: str
user_path: str
rule_path: str
@@ -26,6 +32,16 @@
def ensure_workspac... | https://raw.githubusercontent.com/zhayujie/chatgpt-on-wechat/HEAD/agent/prompt/workspace.py |
Generate documentation strings for clarity |
import os
from typing import Dict, Any
from pathlib import Path
from agent.tools.base_tool import BaseTool, ToolResult
from common.utils import expand_path
class Send(BaseTool):
name: str = "send"
description: str = "Send a LOCAL file (image, video, audio, document) to the user. Only for local file pat... | --- +++ @@ -1,3 +1,6 @@+"""
+Send tool - Send files to the user
+"""
import os
from typing import Dict, Any
@@ -8,6 +11,7 @@
class Send(BaseTool):
+ """Tool for sending files to the user"""
name: str = "send"
description: str = "Send a LOCAL file (image, video, audio, document) to the user. O... | https://raw.githubusercontent.com/zhayujie/chatgpt-on-wechat/HEAD/agent/tools/send/send.py |
Write docstrings for algorithm functions | import json
import os
import time
import threading
from common.log import logger
from agent.protocol.models import LLMRequest, LLMModel
from agent.protocol.agent_stream import AgentStreamExecutor
from agent.protocol.result import AgentAction, AgentActionType, ToolResult, AgentResult
from agent.tools.base_tool import B... | --- +++ @@ -16,6 +16,25 @@ context_reserve_tokens=None, memory_manager=None, name: str = None,
workspace_dir: str = None, skill_manager=None, enable_skills: bool = True,
runtime_info: dict = None):
+ """
+ Initialize the Agent with system prompt, model,... | https://raw.githubusercontent.com/zhayujie/chatgpt-on-wechat/HEAD/agent/protocol/agent.py |
Provide docstrings following PEP 257 |
from bridge.bridge import Bridge
from bridge.context import Context
from bridge.reply import *
from common.log import logger
from config import conf
class Channel(object):
channel_type = ""
NOT_SUPPORT_REPLYTYPE = [ReplyType.VOICE, ReplyType.IMAGE]
def __init__(self):
import threading
se... | --- +++ @@ -1,3 +1,6 @@+"""
+Message sending channel abstract class
+"""
from bridge.bridge import Bridge
from bridge.context import Context
@@ -17,6 +20,9 @@ self.cloud_mode = False # set to True by ChannelManager when running with cloud client
def startup(self):
+ """
+ init channel
... | https://raw.githubusercontent.com/zhayujie/chatgpt-on-wechat/HEAD/channel/channel.py |
Add concise docstrings to each method | import copy
import json
# -*- coding=utf-8 -*-
import logging
import os
import time
import requests
import dingtalk_stream
from dingtalk_stream import AckMessage
from dingtalk_stream.card_replier import AICardReplier
from dingtalk_stream.card_replier import AICardStatus
from dingtalk_stream.card_replier import CardRep... | --- +++ @@ -1,3 +1,9 @@+"""
+钉钉通道接入
+
+@author huiwen
+@Date 2023/11/28
+"""
import copy
import json
# -*- coding=utf-8 -*-
@@ -35,6 +41,14 @@ recipients: list = None,
support_forward: bool = True,
) -> str:
+ """
+ AI卡片的创建接口
+ :param support_forward:
+ :para... | https://raw.githubusercontent.com/zhayujie/chatgpt-on-wechat/HEAD/channel/dingtalk/dingtalk_channel.py |
Improve my code by adding docstrings |
import os
import platform
from typing import Dict, Optional, List
from agent.skills.types import SkillEntry
def resolve_runtime_platform() -> str:
return platform.system().lower()
def has_binary(bin_name: str) -> bool:
import shutil
return shutil.which(bin_name) is not None
def has_any_binary(bin_nam... | --- +++ @@ -1,3 +1,6 @@+"""
+Configuration support for skills.
+"""
import os
import platform
@@ -6,23 +9,49 @@
def resolve_runtime_platform() -> str:
+ """Get the current runtime platform."""
return platform.system().lower()
def has_binary(bin_name: str) -> bool:
+ """
+ Check if a binary is... | https://raw.githubusercontent.com/zhayujie/chatgpt-on-wechat/HEAD/agent/skills/config.py |
Create docstrings for all classes and functions |
import uuid
from datetime import datetime
from typing import Any, Dict, Optional
from croniter import croniter
from agent.tools.base_tool import BaseTool, ToolResult
from bridge.context import Context, ContextType
from bridge.reply import Reply, ReplyType
from common.log import logger
class SchedulerTool(BaseTool):... | --- +++ @@ -1,3 +1,6 @@+"""
+Scheduler tool for creating and managing scheduled tasks
+"""
import uuid
from datetime import datetime
@@ -11,6 +14,9 @@
class SchedulerTool(BaseTool):
+ """
+ Tool for managing scheduled tasks (reminders, notifications, etc.)
+ """
name: str = "scheduler"
... | https://raw.githubusercontent.com/zhayujie/chatgpt-on-wechat/HEAD/agent/tools/scheduler/scheduler_tool.py |
Document all endpoints with docstrings |
from agent.tools.base_tool import BaseTool
class MemoryGetTool(BaseTool):
name: str = "memory_get"
description: str = (
"Read specific content from memory files. "
"Use this to get full context from a memory file or specific line range."
)
params: dict = {
"type": "object... | --- +++ @@ -1,8 +1,14 @@+"""
+Memory get tool
+
+Allows agents to read specific sections from memory files
+"""
from agent.tools.base_tool import BaseTool
class MemoryGetTool(BaseTool):
+ """Tool for reading memory file contents"""
name: str = "memory_get"
description: str = (
@@ -30,10 +36,2... | https://raw.githubusercontent.com/zhayujie/chatgpt-on-wechat/HEAD/agent/tools/memory/memory_get.py |
Create simple docstrings for beginners | from enum import Enum
from typing import Any, Optional
from common.log import logger
import copy
class ToolStage(Enum):
PRE_PROCESS = "pre_process" # Tools that need to be actively selected by the agent
POST_PROCESS = "post_process" # Tools that automatically execute after final_answer
class ToolResult:
... | --- +++ @@ -5,11 +5,13 @@
class ToolStage(Enum):
+ """Enum representing tool decision stages"""
PRE_PROCESS = "pre_process" # Tools that need to be actively selected by the agent
POST_PROCESS = "post_process" # Tools that automatically execute after final_answer
class ToolResult:
+ """Tool ex... | https://raw.githubusercontent.com/zhayujie/chatgpt-on-wechat/HEAD/agent/tools/base_tool.py |
Provide docstrings following PEP 257 |
from __future__ import annotations
import os
from typing import List, Dict, Optional, Any
from dataclasses import dataclass
from common.log import logger
@dataclass
class ContextFile:
path: str
content: str
class PromptBuilder:
def __init__(self, workspace_dir: str, language: str = "zh"):
... | --- +++ @@ -1,3 +1,8 @@+"""
+System Prompt Builder - 系统提示词构建器
+
+实现模块化的系统提示词构建,支持工具、技能、记忆等多个子系统
+"""
from __future__ import annotations
import os
@@ -9,13 +14,22 @@
@dataclass
class ContextFile:
+ """上下文文件"""
path: str
content: str
class PromptBuilder:
+ """提示词构建器"""
def __init__(... | https://raw.githubusercontent.com/zhayujie/chatgpt-on-wechat/HEAD/agent/prompt/builder.py |
Add standardized docstrings across the file |
import os
import json
from typing import Dict, List, Optional
from pathlib import Path
from common.log import logger
from agent.skills.types import Skill, SkillEntry, SkillSnapshot
from agent.skills.loader import SkillLoader
from agent.skills.formatter import format_skill_entries_for_prompt
SKILLS_CONFIG_FILE = "skil... | --- +++ @@ -1,3 +1,6 @@+"""
+Skill manager for managing skill lifecycle and operations.
+"""
import os
import json
@@ -12,6 +15,7 @@
class SkillManager:
+ """Manages skills for an agent."""
def __init__(
self,
@@ -19,6 +23,13 @@ custom_dir: Optional[str] = None,
config: Optio... | https://raw.githubusercontent.com/zhayujie/chatgpt-on-wechat/HEAD/agent/skills/manager.py |
Add docstrings with type hints explained |
import os
import asyncio
import datetime
import time
from typing import Optional, List
from agent.protocol import Agent
from agent.tools import ToolManager
from common.log import logger
from common.utils import expand_path
class AgentInitializer:
def __init__(self, bridge, agent_bridge):
self.bridg... | --- +++ @@ -1,3 +1,6 @@+"""
+Agent Initializer - Handles agent initialization logic
+"""
import os
import asyncio
@@ -12,12 +15,35 @@
class AgentInitializer:
+ """
+ Handles agent initialization including:
+ - Workspace setup
+ - Memory system initialization
+ - Tool loading
+ - System promp... | https://raw.githubusercontent.com/zhayujie/chatgpt-on-wechat/HEAD/bridge/agent_initializer.py |
Write docstrings for backend logic |
from typing import Dict, Any, Optional, Literal, Tuple
DEFAULT_MAX_LINES = 2000
DEFAULT_MAX_BYTES = 50 * 1024 # 50KB
GREP_MAX_LINE_LENGTH = 500 # Max chars per grep match line
class TruncationResult:
def __init__(
self,
content: str,
truncated: bool,
truncated_by: Optiona... | --- +++ @@ -1,3 +1,12 @@+"""
+Shared truncation utilities for tool outputs.
+
+Truncation is based on two independent limits - whichever is hit first wins:
+- Line limit (default: 2000 lines)
+- Byte limit (default: 50KB)
+
+Never returns partial lines (except bash tail truncation edge case).
+"""
from typing import... | https://raw.githubusercontent.com/zhayujie/chatgpt-on-wechat/HEAD/agent/tools/utils/truncate.py |
Help me write clear docstrings |
import os
from typing import Dict, Any
from pathlib import Path
from agent.tools.base_tool import BaseTool, ToolResult
from agent.tools.utils.truncate import truncate_head, format_size, DEFAULT_MAX_LINES, DEFAULT_MAX_BYTES
from common.utils import expand_path
class Read(BaseTool):
name: str = "read"
de... | --- +++ @@ -1,3 +1,7 @@+"""
+Read tool - Read file contents
+Supports text files, images (jpg, png, gif, webp), and PDF files
+"""
import os
from typing import Dict, Any
@@ -9,6 +13,7 @@
class Read(BaseTool):
+ """Tool for reading file contents"""
name: str = "read"
description: str = f"Read ... | https://raw.githubusercontent.com/zhayujie/chatgpt-on-wechat/HEAD/agent/tools/read/read.py |
Generate docstrings for script automation |
import base64
import hashlib
import json
import math
import os
import threading
import time
import uuid
import requests
import websocket
from bridge.context import Context, ContextType
from bridge.reply import Reply, ReplyType
from channel.chat_channel import ChatChannel, check_prefix
from channel.wecom_bot.wecom_bo... | --- +++ @@ -1,3 +1,11 @@+"""
+WeCom (企业微信) AI Bot channel via WebSocket long connection.
+
+Supports:
+- Single chat and group chat (text / image / file input & output)
+- Scheduled task push via aibot_send_msg
+- Heartbeat keep-alive and auto-reconnect
+"""
import base64
import hashlib
@@ -166,6 +174,7 @@ # --... | https://raw.githubusercontent.com/zhayujie/chatgpt-on-wechat/HEAD/channel/wecom_bot/wecom_bot_channel.py |
Add docstrings with type hints explained |
import difflib
import re
from typing import Optional, Tuple
def strip_bom(text: str) -> Tuple[str, str]:
if text.startswith('\ufeff'):
return '\ufeff', text[1:]
return '', text
def detect_line_ending(text: str) -> str:
if '\r\n' in text:
return '\r\n'
return '\n'
def normalize_to_... | --- +++ @@ -1,3 +1,7 @@+"""
+Diff tools for file editing
+Provides fuzzy matching and diff generation functionality
+"""
import difflib
import re
@@ -5,28 +9,60 @@
def strip_bom(text: str) -> Tuple[str, str]:
+ """
+ Remove BOM (Byte Order Mark)
+
+ :param text: Original text
+ :return: (BOM, te... | https://raw.githubusercontent.com/zhayujie/chatgpt-on-wechat/HEAD/agent/tools/utils/diff.py |
Write documentation strings for class attributes | from __future__ import annotations
import time
import uuid
from dataclasses import dataclass, field
from enum import Enum
from typing import List, Dict, Any, Optional
from agent.protocol.task import Task, TaskStatus
class AgentActionType(Enum):
TOOL_USE = "tool_use"
THINKING = "thinking"
FINAL_ANSWER = "... | --- +++ @@ -9,6 +9,7 @@
class AgentActionType(Enum):
+ """Enum representing different types of agent actions."""
TOOL_USE = "tool_use"
THINKING = "thinking"
FINAL_ANSWER = "final_answer"
@@ -16,6 +17,17 @@
@dataclass
class ToolResult:
+ """
+ Represents the result of a tool use.
+
+ ... | https://raw.githubusercontent.com/zhayujie/chatgpt-on-wechat/HEAD/agent/protocol/result.py |
Improve documentation using docstrings |
import base64
import os
import subprocess
import tempfile
from typing import Any, Dict, Optional, Tuple
import requests
from agent.tools.base_tool import BaseTool, ToolResult
from common.log import logger
from config import conf
DEFAULT_MODEL = "gpt-4.1-mini"
DEFAULT_TIMEOUT = 60
MAX_TOKENS = 1000
COMPRESS_THRESHOL... | --- +++ @@ -1,3 +1,8 @@+"""
+Vision tool - Analyze images using OpenAI-compatible Vision API.
+Supports local files (auto base64-encoded) and HTTP URLs.
+Providers: OpenAI (preferred) > LinkAI (fallback).
+"""
import base64
import os
@@ -26,6 +31,7 @@
class Vision(BaseTool):
+ """Analyze images using OpenAI-... | https://raw.githubusercontent.com/zhayujie/chatgpt-on-wechat/HEAD/agent/tools/vision/vision.py |
Please document this code using docstrings |
import time
import threading
from datetime import datetime, timedelta
from typing import Callable, Optional
from croniter import croniter
from common.log import logger
class SchedulerService:
def __init__(self, task_store, execute_callback: Callable):
self.task_store = task_store
self.execut... | --- +++ @@ -1,3 +1,6 @@+"""
+Background scheduler service for executing scheduled tasks
+"""
import time
import threading
@@ -8,8 +11,18 @@
class SchedulerService:
+ """
+ Background service that executes scheduled tasks
+ """
def __init__(self, task_store, execute_callback: Callable):
+ ... | https://raw.githubusercontent.com/zhayujie/chatgpt-on-wechat/HEAD/agent/tools/scheduler/scheduler_service.py |
Add docstrings that explain logic |
import os
from typing import Dict, Any
from agent.tools.base_tool import BaseTool, ToolResult
from agent.tools.utils.truncate import truncate_head, format_size, DEFAULT_MAX_BYTES
from common.utils import expand_path
DEFAULT_LIMIT = 500
class Ls(BaseTool):
name: str = "ls"
description: str = f"List di... | --- +++ @@ -1,3 +1,6 @@+"""
+Ls tool - List directory contents
+"""
import os
from typing import Dict, Any
@@ -11,6 +14,7 @@
class Ls(BaseTool):
+ """Tool for listing directory contents"""
name: str = "ls"
description: str = f"List directory contents. Returns entries sorted alphabetically, wi... | https://raw.githubusercontent.com/zhayujie/chatgpt-on-wechat/HEAD/agent/tools/ls/ls.py |
Write docstrings including parameters and return values |
from __future__ import annotations
from typing import Dict, List, Set
from common.log import logger
# ------------------------------------------------------------------ #
# Claude-format sanitizer (used by agent_stream)
# ------------------------------------------------------------------ #
def sanitize_claude_mes... | --- +++ @@ -1,3 +1,16 @@+"""
+Message sanitizer — fix broken tool_use / tool_result pairs.
+
+Provides two public helpers that can be reused across agent_stream.py
+and any bot that converts messages to OpenAI format:
+
+1. sanitize_claude_messages(messages)
+ Operates on the internal Claude-format message list (in-p... | https://raw.githubusercontent.com/zhayujie/chatgpt-on-wechat/HEAD/agent/protocol/message_utils.py |
Add docstrings that explain logic | import os
import re
import base64
import requests
from bridge.context import ContextType
from channel.chat_message import ChatMessage
from common.log import logger
from common.utils import expand_path
from config import conf
from Crypto.Cipher import AES
MAGIC_SIGNATURES = [
(b"%PDF", ".pdf"),
(b"\x89PNG\r\n... | --- +++ @@ -34,6 +34,7 @@
def _guess_ext_from_bytes(data: bytes) -> str:
+ """Guess file extension from file content magic bytes."""
if not data or len(data) < 8:
return ""
for sig, ext in MAGIC_SIGNATURES:
@@ -53,6 +54,10 @@
def _decrypt_media(url: str, aeskey: str) -> bytes:
+ """
+ ... | https://raw.githubusercontent.com/zhayujie/chatgpt-on-wechat/HEAD/channel/wecom_bot/wecom_bot_message.py |
Generate descriptive docstrings automatically |
from common.log import logger
class AgentEventHandler:
def __init__(self, context=None, original_callback=None):
self.context = context
self.original_callback = original_callback
# Get channel for sending intermediate messages
self.channel = None
if context:
... | --- +++ @@ -1,10 +1,23 @@+"""
+Agent Event Handler - Handles agent events and thinking process output
+"""
from common.log import logger
class AgentEventHandler:
+ """
+ Handles agent events and optionally sends intermediate messages to channel
+ """
def __init__(self, context=None, original... | https://raw.githubusercontent.com/zhayujie/chatgpt-on-wechat/HEAD/bridge/agent_event_handler.py |
Write docstrings describing functionality |
import base64
import json
import os
import threading
import time
import requests
import websocket
from bridge.context import Context, ContextType
from bridge.reply import Reply, ReplyType
from channel.chat_channel import ChatChannel, check_prefix
from channel.qq.qq_message import QQMessage
from common.expired_dict i... | --- +++ @@ -1,3 +1,11 @@+"""
+QQ Bot channel via WebSocket long connection.
+
+Supports:
+- Group chat (@bot), single chat (C2C), guild channel, guild DM
+- Text / image / file message send & receive
+- Heartbeat keep-alive and auto-reconnect with session resume
+"""
import base64
import json
@@ -474,6 +482,7 @@ ... | https://raw.githubusercontent.com/zhayujie/chatgpt-on-wechat/HEAD/channel/qq/qq_channel.py |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.