instruction stringclasses 100
values | code stringlengths 78 193k | response stringlengths 259 170k | file stringlengths 59 203 |
|---|---|---|---|
Create documentation strings for testing functions | from __future__ import annotations
from collections import Counter
from pathlib import Path
from typing import ClassVar
from msgspec import Struct
from webapp.display.page import Page
class Stemmer:
STOP_WORDS: ClassVar[set[str]] = set(
"a about above after again against all am an and any are aren't as... | --- +++ @@ -59,11 +59,13 @@
@property
def weighted_text(self) -> str:
+ """Return the text with the title repeated."""
return " ".join(
[self.title] * self.TITLE_WEIGHT + [self.text] * self.BODY_WEIGHT
)
def _term_frequency(self, stemmer: Stemmer) -> None:
+ ... | https://raw.githubusercontent.com/sanic-org/sanic/HEAD/guide/webapp/display/search/search.py |
Write docstrings for backend logic |
import sys
from functools import partial
from importlib import import_module
from inspect import ismodule
try:
from ujson import dumps as ujson_dumps
json_dumps = partial(ujson_dumps, escape_forward_slashes=False)
except ImportError:
# This is done in order to ensure that the JSON response is
# kep... | --- +++ @@ -1,3 +1,4 @@+"""Defines basics of HTTP standard."""
import sys
@@ -113,18 +114,35 @@
def has_message_body(status):
+ """
+ According to the following RFC message body and length SHOULD NOT
+ be included in responses status 1XX, 204 and 304.
+ https://tools.ietf.org/html/rfc2616#section-4... | https://raw.githubusercontent.com/sanic-org/sanic/HEAD/sanic/helpers.py |
Create documentation strings for testing functions | from __future__ import annotations
import logging
from dataclasses import dataclass, field
from pathlib import Path
from socket import socket
from ssl import SSLContext
from typing import TYPE_CHECKING, Any
from sanic.application.constants import Mode, Server, ServerStage
from sanic.log import VerbosityFilter, logge... | --- +++ @@ -19,6 +19,7 @@
@dataclass
class ApplicationServerInfo:
+ """Information about a server instance."""
settings: dict[str, Any]
stage: ServerStage = field(default=ServerStage.STOPPED)
@@ -27,6 +28,11 @@
@dataclass
class ApplicationState:
+ """Application state.
+
+ This class is used ... | https://raw.githubusercontent.com/sanic-org/sanic/HEAD/sanic/application/state.py |
Generate docstrings for exported functions | from __future__ import annotations
from typing import TYPE_CHECKING
if TYPE_CHECKING:
from sanic.request import Request
from sanic.response import BaseHTTPResponse
from asyncio import CancelledError, sleep
from time import perf_counter
from sanic.compat import Header
from sanic.exceptions import (
BadR... | --- +++ @@ -31,6 +31,17 @@
class Http(Stream, metaclass=TouchUpMeta):
+ """ "Internal helper for managing the HTTP/1.1 request/response cycle.
+
+ Raises:
+ BadRequest: If the request body is malformed.
+ Exception: If the request is malformed.
+ ExpectationFailed: If the request is malfo... | https://raw.githubusercontent.com/sanic-org/sanic/HEAD/sanic/http/http1.py |
Add docstrings to improve collaboration | from __future__ import annotations
from sanic.errorpages import BaseRenderer, TextRenderer, exception_response
from sanic.exceptions import ServerError
from sanic.log import error_logger
from sanic.models.handler_types import RouteHandler
from sanic.request.types import Request
from sanic.response import text
from san... | --- +++ @@ -10,6 +10,16 @@
class ErrorHandler:
+ """Process and handle all uncaught exceptions.
+
+ This error handling framework is built into the core that can be extended
+ by the developers to perform a wide range of tasks from recording the error
+ stats to reporting them to an external service tha... | https://raw.githubusercontent.com/sanic-org/sanic/HEAD/sanic/handlers/error.py |
Add docstrings to existing functions | from __future__ import annotations
import re
from collections.abc import Iterable
from typing import Any
from urllib.parse import unquote
from sanic.exceptions import InvalidHeader
from sanic.helpers import STATUS_CODES
# TODO:
# - the Options object should be a typed object to allow for less casting
# across th... | --- +++ @@ -34,6 +34,21 @@
class MediaType:
+ """A media type, as used in the Accept header.
+
+ This class is a representation of a media type, as used in the Accept
+ header. It encapsulates the type, subtype and any parameters, and
+ provides methods for matching against other media types.
+
+ Two... | https://raw.githubusercontent.com/sanic-org/sanic/HEAD/sanic/headers.py |
Create docstrings for each class method | import re
from typing import Any
from sanic.cookies.response import Cookie
from sanic.request.parameters import RequestParameters
COOKIE_NAME_RESERVED_CHARS = re.compile(
'[\x00-\x1f\x7f-\xff()<>@,;:\\\\"/[\\]?={} \x09]'
)
OCTAL_PATTERN = re.compile(r"\\[0-3][0-7][0-7]")
QUOTE_PATTERN = re.compile(r"[\\].")
d... | --- +++ @@ -48,6 +48,27 @@
def parse_cookie(raw: str) -> dict[str, list[str]]:
+ """Parses a raw cookie string into a dictionary.
+
+ The function takes a raw cookie string (usually from HTTP headers) and
+ returns a dictionary where each key is a cookie name and the value is a
+ list of values for that... | https://raw.githubusercontent.com/sanic-org/sanic/HEAD/sanic/cookies/request.py |
Create Google-style docstrings for my code | from __future__ import annotations
import asyncio
import logging
import logging.config
import re
import sys
from asyncio import (
AbstractEventLoop,
CancelledError,
Task,
ensure_future,
get_running_loop,
wait_for,
)
from asyncio.futures import Future
from collections import defaultdict, deque
... | --- +++ @@ -114,6 +114,60 @@ CommandMixin,
metaclass=TouchUpMeta,
):
+ """The main application instance
+
+ You will create an instance of this class and use it to register
+ routes, listeners, middleware, blueprints, error handlers, etc.
+
+ By convention, it is often called `app`. It must be nam... | https://raw.githubusercontent.com/sanic-org/sanic/HEAD/sanic/app.py |
Add well-formatted docstrings | from __future__ import annotations
import asyncio
from abc import ABC, abstractmethod
from ssl import SSLContext
from typing import TYPE_CHECKING, Any, Callable, cast
from sanic.compat import Header
from sanic.constants import LocalCertCreator
from sanic.exceptions import (
BadRequest,
PayloadTooLarge,
S... | --- +++ @@ -50,6 +50,7 @@
class HTTP3Transport(TransportProtocol):
+ """HTTP/3 transport implementation."""
__slots__ = ("_protocol",)
@@ -73,6 +74,7 @@
class Receiver(ABC):
+ """HTTP/3 receiver base class."""
future: asyncio.Future
@@ -87,6 +89,7 @@
class HTTPReceiver(Receiver, Stre... | https://raw.githubusercontent.com/sanic-org/sanic/HEAD/sanic/http/http3.py |
Add docstrings to improve readability | from __future__ import annotations
import warnings
from typing import TYPE_CHECKING
from sanic.compat import Header
from sanic.exceptions import BadRequest, ServerError
from sanic.helpers import Default
from sanic.http import Stage
from sanic.log import error_logger, logger
from sanic.models.asgi import ASGIReceive,... | --- +++ @@ -47,6 +47,14 @@ )
async def startup(self) -> None:
+ """
+ Gather the listeners to fire on server start.
+ Because we are using a third-party server and not Sanic server, we do
+ not have access to fire anything BEFORE the server starts.
+ Therefore, we f... | https://raw.githubusercontent.com/sanic-org/sanic/HEAD/sanic/asgi.py |
Add docstrings to incomplete code | from asyncio import CancelledError
from collections.abc import Sequence
from os import PathLike
from typing import Any
from sanic.helpers import STATUS_CODES
from sanic.models.protocol_types import Range
class RequestCancelled(CancelledError):
quiet = True
class ServerKilled(Exception):
quiet = True
cla... | --- +++ @@ -12,11 +12,46 @@
class ServerKilled(Exception):
+ """Exception Sanic server uses when killing a server process for something unexpected happening.""" # noqa: E501
quiet = True
class SanicException(Exception):
+ """Generic exception that will generate an HTTP response when raised in the... | https://raw.githubusercontent.com/sanic-org/sanic/HEAD/sanic/exceptions.py |
Generate docstrings with parameter types | import asyncio
import os
import platform
import signal
import sys
from collections.abc import Awaitable
from contextlib import contextmanager
from enum import Enum
from typing import Literal
from multidict import CIMultiDict # type: ignore
from sanic.helpers import Default
from sanic.log import error_logger
Start... | --- +++ @@ -42,6 +42,7 @@
class UpperStrEnum(StrEnum):
+ """Base class for string enums that are case insensitive."""
def _generate_next_value_(name, start, count, last_values):
return name.upper()
@@ -75,6 +76,11 @@
def pypy_os_module_patch() -> None:
+ """
+ The PyPy os module is miss... | https://raw.githubusercontent.com/sanic-org/sanic/HEAD/sanic/compat.py |
Add well-formatted docstrings | from __future__ import annotations
import os
import signal
import sys
from argparse import ArgumentParser
from contextlib import suppress
from pathlib import Path
from sanic.worker.daemon import Daemon
def _add_target_args(parser: ArgumentParser) -> None:
group = parser.add_mutually_exclusive_group(required=Tr... | --- +++ @@ -28,6 +28,7 @@
def make_kill_parser(parser: ArgumentParser) -> None:
+ """Kill command always sends SIGKILL."""
_add_target_args(parser)
@@ -42,6 +43,15 @@ def resolve_target(
pid: int | None, pidfile: str | None
) -> tuple[int, Path | None]:
+ """
+ Resolve a PID from either a di... | https://raw.githubusercontent.com/sanic-org/sanic/HEAD/sanic/cli/daemon.py |
Add docstrings to clarify complex logic | from __future__ import annotations
import asyncio
from collections import defaultdict
from collections.abc import Iterable, Iterator, MutableSequence, Sequence
from copy import deepcopy
from functools import partial, wraps
from inspect import isfunction
from itertools import chain
from types import SimpleNamespace
fr... | --- +++ @@ -35,6 +35,13 @@
def lazy(func, as_decorator=True):
+ """Decorator to register a function to be called later.
+
+ Args:
+ func (Callable): Function to be called later.
+ as_decorator (bool): Whether the function should be called
+ immediately or not.
+ """
@wraps(f... | https://raw.githubusercontent.com/sanic-org/sanic/HEAD/sanic/blueprints.py |
Write documentation strings for class attributes | from __future__ import annotations
import os
import ssl
from collections.abc import Iterable
from typing import Any
from sanic.log import logger
# Only allow secure ciphers, notably leaving out AES-CBC mode
# OpenSSL chooses ECDSA or RSA depending on the cert in use
CIPHERS_TLS12 = [
"ECDHE-ECDSA-CHACHA20-POLY... | --- +++ @@ -27,6 +27,7 @@ password: str | None = None,
purpose: ssl.Purpose = ssl.Purpose.CLIENT_AUTH,
) -> ssl.SSLContext:
+ """Create a context with secure crypto and HTTP/1.1 in protocols."""
context = ssl.create_default_context(purpose=purpose)
context.minimum_version = ssl.TLSVersion.TLSv1_2... | https://raw.githubusercontent.com/sanic-org/sanic/HEAD/sanic/http/tls/context.py |
Add docstrings that explain inputs and outputs | from __future__ import annotations
import logging
import os
import re
from sanic.helpers import is_atty, json_dumps
from sanic.logging.color import LEVEL_COLORS
from sanic.logging.color import Colors as c
CONTROL_RE = re.compile(r"\033\[[0-9;]*\w")
CONTROL_LIMIT_IDENT = "\033[1000D\033[{limit}C"
CONTROL_LIMIT_START... | --- +++ @@ -28,6 +28,13 @@
class AutoFormatter(logging.Formatter):
+ """
+ Automatically sets up the formatter based on the environment.
+
+ It will switch between the Debug and Production formatters based upon
+ how the environment is set up. Additionally, it will automatically
+ detect if the outpu... | https://raw.githubusercontent.com/sanic-org/sanic/HEAD/sanic/logging/formatter.py |
Document functions with detailed explanations |
from __future__ import annotations
import sys
import typing as t
from functools import partial
from traceback import extract_tb
from sanic.exceptions import BadRequest, SanicException
from sanic.helpers import STATUS_CODES
from sanic.log import deprecation, logger
from sanic.pages.error import ErrorPage
from sanic.... | --- +++ @@ -1,3 +1,17 @@+"""
+Sanic `provides a pattern
+<https://sanicframework.org/guide/best-practices/exceptions.html#using-sanic-exceptions>`_
+for providing a response when an exception occurs. However, if you do no handle
+an exception, it will provide a fallback. There are three fallback types:
+
+- HTML - *def... | https://raw.githubusercontent.com/sanic-org/sanic/HEAD/sanic/errorpages.py |
Generate documentation strings for clarity | from __future__ import annotations
from ast import NodeVisitor, Return, parse
from collections.abc import Iterable
from contextlib import suppress
from inspect import getsource, signature
from textwrap import dedent
from typing import (
Any,
Callable,
cast,
)
from sanic_routing.route import Route
from sa... | --- +++ @@ -54,6 +54,53 @@ error_format: str | None = None,
**ctx_kwargs: Any,
) -> RouteWrapper:
+ """Decorate a function to be registered as a route.
+
+ Args:
+ uri (str): Path of the URL.
+ methods (Optional[Iterable[str]]): List or tuple of
+ ... | https://raw.githubusercontent.com/sanic-org/sanic/HEAD/sanic/mixins/routes.py |
Improve documentation using docstrings | from __future__ import annotations
from collections.abc import Coroutine
from enum import Enum
from typing import Any, Callable
from sanic.base.meta import SanicMeta
from sanic.models.futures import FutureSignal
from sanic.models.handler_types import SignalHandler
from sanic.signals import Event, Signal
from sanic.ty... | --- +++ @@ -27,6 +27,28 @@ exclusive: bool = True,
priority: int = 0,
) -> Callable[[SignalHandler], SignalHandler]:
+ """
+ For creating a signal handler, used similar to a route handler:
+
+ .. code-block:: python
+
+ @app.signal("foo.bar.<thing>")
+ as... | https://raw.githubusercontent.com/sanic-org/sanic/HEAD/sanic/mixins/signals.py |
Add standardized docstrings across the file | from __future__ import annotations
import sys
from typing import TYPE_CHECKING
from sanic.http.constants import HTTP
from sanic.http.http3 import Http3
from sanic.touchup.meta import TouchUpMeta
if TYPE_CHECKING:
from sanic.app import Sanic
from asyncio import CancelledError
from time import monotonic as cur... | --- +++ @@ -84,6 +84,10 @@
class HttpProtocol(HttpProtocolMixin, SanicProtocol, metaclass=TouchUpMeta):
+ """
+ This class provides implements the HTTP 1.1 protocol on top of our
+ Sanic Server transport
+ """
HTTP_CLASS = Http
@@ -142,6 +146,12 @@ self._callback_check_timeouts = None
... | https://raw.githubusercontent.com/sanic-org/sanic/HEAD/sanic/server/protocols/http_protocol.py |
Document all endpoints with docstrings | from __future__ import annotations
from collections import deque
from collections.abc import Sequence
from enum import IntEnum, auto
from itertools import count
from sanic.models.handler_types import MiddlewareType
class MiddlewareLocation(IntEnum):
REQUEST = auto()
RESPONSE = auto()
class Middleware:
... | --- +++ @@ -14,6 +14,16 @@
class Middleware:
+ """Middleware object that is used to encapsulate middleware functions.
+
+ This should generally not be instantiated directly, but rather through
+ the `sanic.Sanic.middleware` decorator and its variants.
+
+ Args:
+ func (MiddlewareType): The middle... | https://raw.githubusercontent.com/sanic-org/sanic/HEAD/sanic/middleware.py |
Document functions with detailed explanations | from __future__ import annotations
import os
import platform
from asyncio import (
AbstractEventLoop,
CancelledError,
Protocol,
all_tasks,
get_event_loop,
get_running_loop,
new_event_loop,
)
from collections.abc import Mapping
from contextlib import suppress
from functools import partial
f... | --- +++ @@ -94,6 +94,14 @@ START_METHOD_SET: ClassVar[bool] = False
def setup_loop(self) -> None:
+ """Set up the event loop.
+
+ An internal method that sets up the event loop to uvloop if
+ possible, or a Windows selector loop if on Windows.
+
+ Returns:
+ None
+ ... | https://raw.githubusercontent.com/sanic-org/sanic/HEAD/sanic/mixins/startup.py |
Fill in missing docstrings in my code | from __future__ import annotations
from typing import Any, Callable
from sanic.base.meta import SanicMeta
from sanic.models.futures import FutureException
class ExceptionMixin(metaclass=SanicMeta):
def __init__(self, *args, **kwargs) -> None:
self._future_exceptions: set[FutureException] = set()
de... | --- +++ @@ -18,6 +18,53 @@ *exceptions: type[Exception] | list[type[Exception]],
apply: bool = True,
) -> Callable:
+ """Decorator used to register an exception handler for the current application or blueprint instance.
+
+ This method allows you to define a handler for specific exce... | https://raw.githubusercontent.com/sanic-org/sanic/HEAD/sanic/mixins/exceptions.py |
Help me comply with documentation standards | from __future__ import annotations
from enum import Enum, auto
from functools import partial
from typing import Callable, cast, overload
from sanic.base.meta import SanicMeta
from sanic.exceptions import BadRequest
from sanic.models.futures import FutureListener
from sanic.models.handler_types import ListenerType, Sa... | --- +++ @@ -65,10 +65,58 @@ ListenerType[Sanic]
| Callable[[ListenerType[Sanic]], ListenerType[Sanic]]
):
+ """Create a listener for a specific event in the application's lifecycle.
+
+ See [Listeners](/en/guide/basics/listeners) for more details.
+
+ .. note::
+ Ov... | https://raw.githubusercontent.com/sanic-org/sanic/HEAD/sanic/mixins/listeners.py |
Write docstrings for this repository | from __future__ import annotations
from collections import deque
from functools import partial
from operator import attrgetter
from typing import Callable, overload
from sanic.base.meta import SanicMeta
from sanic.middleware import Middleware, MiddlewareLocation
from sanic.models.futures import FutureMiddleware, Midd... | --- +++ @@ -48,6 +48,39 @@ *,
priority: int = 0,
) -> MiddlewareType | Callable[[MiddlewareType], MiddlewareType]:
+ """Decorator for registering middleware.
+
+ Decorate and register middleware to be called before a request is
+ handled or after a response is created. Can eit... | https://raw.githubusercontent.com/sanic-org/sanic/HEAD/sanic/mixins/middleware.py |
Add docstrings to existing functions | import asyncio
from os import getenv
from sanic.compat import OS_IS_WINDOWS
from sanic.log import error_logger
from sanic.utils import str_to_bool
def try_use_uvloop() -> None:
if OS_IS_WINDOWS:
error_logger.warning(
"You are trying to use uvloop, but uvloop is not compatible "
"... | --- +++ @@ -8,6 +8,7 @@
def try_use_uvloop() -> None:
+ """Use uvloop instead of the default asyncio loop."""
if OS_IS_WINDOWS:
error_logger.warning(
"You are trying to use uvloop, but uvloop is not compatible "
@@ -47,6 +48,7 @@
def try_windows_loop():
+ """Try to use the Windo... | https://raw.githubusercontent.com/sanic-org/sanic/HEAD/sanic/server/loop.py |
Annotate my code with docstrings | from __future__ import annotations
import email.utils
import unicodedata
from typing import NamedTuple
from urllib.parse import unquote
from sanic.headers import parse_content_header
from sanic.log import logger
from .parameters import RequestParameters
class File(NamedTuple):
type: str
body: bytes
n... | --- +++ @@ -13,6 +13,16 @@
class File(NamedTuple):
+ """Model for defining a file.
+
+ It is a `namedtuple`, therefore you can iterate over the object, or
+ access the parameters by name.
+
+ Args:
+ type (str, optional): The mimetype, defaults to "text/plain".
+ body (bytes): Bytes of the... | https://raw.githubusercontent.com/sanic-org/sanic/HEAD/sanic/request/form.py |
Generate consistent documentation across files | from __future__ import annotations
from typing import TYPE_CHECKING
from sanic.exceptions import RequestCancelled
if TYPE_CHECKING:
from sanic.app import Sanic
import asyncio
from asyncio.transports import Transport
from time import monotonic as current_time
from sanic.log import error_logger
from sanic.mode... | --- +++ @@ -65,6 +65,9 @@ return None
async def send(self, data):
+ """
+ Generic data write implementation with backpressure control.
+ """
await self._can_write.wait()
if self.transport.is_closing():
raise RequestCancelled
@@ -72,11 +75,17 @@ ... | https://raw.githubusercontent.com/sanic-org/sanic/HEAD/sanic/server/protocols/base_protocol.py |
Generate docstrings for exported functions | from __future__ import annotations
from collections.abc import Sequence
from email.utils import formatdate
from functools import partial, wraps
from os import PathLike, path
from pathlib import Path, PurePath
from urllib.parse import unquote
from sanic_routing.route import Route
from sanic.base.meta import SanicMeta... | --- +++ @@ -49,6 +49,77 @@ follow_external_symlink_files: bool = False,
follow_external_symlink_dirs: bool = False,
):
+ """Register a root to serve files from. The input can either be a file or a directory.
+
+ This method provides an easy and simple way to set up the route necessar... | https://raw.githubusercontent.com/sanic-org/sanic/HEAD/sanic/mixins/static.py |
Auto-generate documentation strings for this file | from __future__ import annotations
import secrets
import socket
import stat
from ipaddress import ip_address
from pathlib import Path
from typing import Any
from sanic.http.constants import HTTP
def bind_socket(host: str, port: int, *, backlog=100) -> socket.socket:
location = (host, port)
# socket.share, ... | --- +++ @@ -12,6 +12,12 @@
def bind_socket(host: str, port: int, *, backlog=100) -> socket.socket:
+ """Create TCP server socket.
+ :param host: IPv4, IPv6 or hostname may be specified
+ :param port: TCP port number
+ :param backlog: Maximum number of connections to queue
+ :return: socket.socket obj... | https://raw.githubusercontent.com/sanic-org/sanic/HEAD/sanic/server/socket.py |
Write docstrings for this repository | from __future__ import annotations
from collections.abc import Iterable
from functools import lru_cache
from inspect import signature
from typing import Any
from uuid import UUID
from sanic_routing import BaseRouter
from sanic_routing.exceptions import NoMethod
from sanic_routing.exceptions import NotFound as Routing... | --- +++ @@ -23,6 +23,7 @@
class Router(BaseRouter):
+ """The router implementation responsible for routing a `Request` object to the appropriate handler.""" # noqa: E501
DEFAULT_METHOD = "GET"
ALLOWED_METHODS = HTTP_METHODS
@@ -51,6 +52,26 @@ def get( # type: ignore
self, path: str, me... | https://raw.githubusercontent.com/sanic-org/sanic/HEAD/sanic/router.py |
Help me comply with documentation standards | import asyncio
import secrets
from collections.abc import AsyncIterator, Iterable, Mapping, Sequence
from websockets.exceptions import (
ConnectionClosed,
ConnectionClosedError,
ConnectionClosedOK,
)
from websockets.frames import Frame, Opcode
try: # websockets >= 11.0
from websockets.protocol impo... | --- +++ @@ -154,6 +154,14 @@ )
async def wait_for_connection_lost(self, timeout=None) -> bool:
+ """
+ Wait until the TCP connection is closed or ``timeout`` elapses.
+ If timeout is None, wait forever.
+ Recommend you should pass in self.close_timeout as timeout
+
+ Re... | https://raw.githubusercontent.com/sanic-org/sanic/HEAD/sanic/server/websockets/impl.py |
Add docstrings including usage examples | from __future__ import annotations
from collections.abc import Iterable
from typing import (
TYPE_CHECKING,
Any,
Callable,
)
from sanic.models.handler_types import RouteHandler
from sanic.request.types import Request
if TYPE_CHECKING:
from sanic import Sanic
from sanic.blueprints import Blueprin... | --- +++ @@ -17,6 +17,100 @@
class HTTPMethodView:
+ """Class based implementation for creating and grouping handlers
+
+ Class-based views (CBVs) are an alternative to function-based views. They
+ allow you to reuse common logic, and group related views, while keeping
+ the flexibility of function-based... | https://raw.githubusercontent.com/sanic-org/sanic/HEAD/sanic/views.py |
Add docstrings with type hints explained | import asyncio
import codecs
from collections.abc import AsyncIterator
from typing import TYPE_CHECKING
from websockets.frames import Frame, Opcode
from websockets.typing import Data
from sanic.exceptions import ServerError
if TYPE_CHECKING:
from .impl import WebsocketImplProtocol
UTF8Decoder = codecs.getincr... | --- +++ @@ -17,6 +17,11 @@
class WebsocketFrameAssembler:
+ """
+ Assemble a message from frames.
+ Code borrowed from aaugustin/websockets project:
+ https://github.com/aaugustin/websockets/blob/6eb98dd8fa5b2c896b9f6be7e8d117708da82a39/src/websockets/sync/messages.py
+ """
__slots__ = (
... | https://raw.githubusercontent.com/sanic-org/sanic/HEAD/sanic/server/websockets/frame.py |
Generate consistent docstrings | from __future__ import annotations
from datetime import datetime, timezone
from email.utils import formatdate, parsedate_to_datetime
from mimetypes import guess_type
from os import path
from pathlib import PurePath
from time import time
from typing import Any, AnyStr, Callable
from urllib.parse import quote_plus
from... | --- +++ @@ -21,6 +21,15 @@ def empty(
status: int = 204, headers: dict[str, str] | None = None
) -> HTTPResponse:
+ """Returns an empty response to the client.
+
+ Args:
+ status (int, optional): HTTP response code. Defaults to `204`.
+ headers ([type], optional): Custom HTTP headers. Defaults... | https://raw.githubusercontent.com/sanic-org/sanic/HEAD/sanic/response/convenience.py |
Generate docstrings for exported functions | from __future__ import annotations
from asyncio import BaseProtocol
from collections import defaultdict
from contextvars import ContextVar
from inspect import isawaitable
from types import SimpleNamespace
from typing import (
TYPE_CHECKING,
Any,
Generic,
cast,
)
from sanic_routing.route import Route
f... | --- +++ @@ -84,6 +84,18 @@
class Request(Generic[sanic_type, ctx_type]):
+ """State of HTTP request.
+
+ Args:
+ url_bytes (bytes): Raw URL bytes.
+ headers (Header): Request headers.
+ version (str): HTTP version.
+ method (str): HTTP method.
+ transport (TransportProtocol)... | https://raw.githubusercontent.com/sanic-org/sanic/HEAD/sanic/request/types.py |
Write documentation strings for class attributes | from __future__ import annotations
from multiprocessing.connection import Connection
from os import environ, getpid
from typing import Any, Callable
from sanic.log import Colors, logger
from sanic.worker.process import ProcessState
from sanic.worker.state import WorkerState
class WorkerMultiplexer:
def __init_... | --- +++ @@ -10,6 +10,15 @@
class WorkerMultiplexer:
+ """Multiplexer for Sanic workers.
+
+ This is instantiated inside of worker porocesses only. It is used to
+ communicate with the monitor process.
+
+ Args:
+ monitor_publisher (Connection): The connection to the monitor.
+ worker_state... | https://raw.githubusercontent.com/sanic-org/sanic/HEAD/sanic/worker/multiplexer.py |
Add documentation for all methods | from __future__ import annotations
from collections.abc import Coroutine, Iterator
from datetime import datetime
from typing import (
TYPE_CHECKING,
Any,
AnyStr,
Callable,
TypeVar,
)
from sanic.compat import Header
from sanic.cookies import CookieJar
from sanic.cookies.response import Cookie, Same... | --- +++ @@ -27,6 +27,7 @@
class BaseHTTPResponse:
+ """The base class for all HTTP Responses"""
__slots__ = (
"asgi",
@@ -60,12 +61,26 @@
@property
def cookies(self) -> CookieJar:
+ """The response cookies.
+
+ See [Cookies](/en/guide/basics/cookies.html)
+
+ Retur... | https://raw.githubusercontent.com/sanic-org/sanic/HEAD/sanic/response/types.py |
Write docstrings for this repository | import types
from importlib.util import module_from_spec, spec_from_file_location
from os import environ as os_environ
from pathlib import Path
from re import findall as re_findall
from sanic.exceptions import LoadFileException, PyFileError
from sanic.helpers import import_string
def str_to_bool(val: str) -> bool:
... | --- +++ @@ -10,6 +10,16 @@
def str_to_bool(val: str) -> bool:
+ """Takes string and tries to turn it into bool as human would do.
+
+ If val is in case insensitive (
+ "y", "yes", "yep", "yup", "t",
+ "true", "on", "enable", "enabled", "1"
+ ) returns True.
+ If val is in case insensitive ... | https://raw.githubusercontent.com/sanic-org/sanic/HEAD/sanic/utils.py |
Fully document this Python code with docstrings | from __future__ import annotations
import atexit
import grp
import os
import pwd
import signal
import sys
import time
import uuid
from dataclasses import dataclass
from pathlib import Path
from sanic.compat import OS_IS_WINDOWS
from sanic.log import logger
try:
import fcntl # type: ignore
except (ImportError,... | --- +++ @@ -23,6 +23,15 @@
def _get_default_runtime_dir() -> Path:
+ """
+ Default directory for auto-generated runtime artifacts (pid/lock/log).
+
+ Priority:
+ 1) XDG_RUNTIME_DIR/sanic (preferred, runtime-only)
+ 2) ~/.local/state/sanic (persistent state, modern default)
+ 3) ~/.cache/s... | https://raw.githubusercontent.com/sanic-org/sanic/HEAD/sanic/worker/daemon.py |
Improve documentation using docstrings | from __future__ import annotations
from collections.abc import Mapping
from datetime import datetime
from inspect import isawaitable
from multiprocessing.connection import Connection
from os import environ
from pathlib import Path
from typing import Any
from sanic.exceptions import Unauthorized
from sanic.helpers imp... | --- +++ @@ -16,6 +16,26 @@
class Inspector:
+ """Inspector for Sanic workers.
+
+ This class is used to create an inspector for Sanic workers. It is
+ instantiated by the worker class and is used to create a Sanic app
+ that can be used to inspect and control the workers and the server.
+
+ It is not... | https://raw.githubusercontent.com/sanic-org/sanic/HEAD/sanic/worker/inspector.py |
Improve my code by adding docstrings | from __future__ import annotations
import os
import signal
from collections.abc import Iterable, MutableMapping
from contextlib import suppress
from enum import IntEnum, auto
from itertools import chain, count
from multiprocessing.connection import Connection
from multiprocessing.context import BaseContext
from rando... | --- +++ @@ -35,6 +35,29 @@
class WorkerManager:
+ """Manage all of the processes.
+
+ This class is used to manage all of the processes. It is instantiated
+ by Sanic when in multiprocess mode (which is OOTB default) and is used
+ to start, stop, and restart the worker processes.
+
+ You can access i... | https://raw.githubusercontent.com/sanic-org/sanic/HEAD/sanic/worker/manager.py |
Write reusable docstrings | from abc import ABC, abstractmethod
from html5tagger import HTML, Builder, Document
from sanic import __version__ as VERSION
from sanic.application.logo import SVG_LOGO_SIMPLE
from sanic.pages.css import CSS
class BasePage(ABC, metaclass=CSS): # no cov
TITLE = "Sanic"
HEADING = None
CSS: str
doc: ... | --- +++ @@ -8,6 +8,7 @@
class BasePage(ABC, metaclass=CSS): # no cov
+ """Base page for Sanic pages."""
TITLE = "Sanic"
HEADING = None
@@ -19,9 +20,19 @@
@property
def style(self) -> str:
+ """Returns the CSS for the page.
+
+ Returns:
+ str: The CSS for the page.... | https://raw.githubusercontent.com/sanic-org/sanic/HEAD/sanic/pages/base.py |
Please document this code using docstrings | from __future__ import annotations
import asyncio
from collections import deque
from dataclasses import dataclass
from enum import Enum
from inspect import isawaitable
from typing import Any, cast
from sanic_routing import BaseRouter, Route, RouteGroup
from sanic_routing.exceptions import NotFound
from sanic_routing... | --- +++ @@ -18,6 +18,7 @@
class Event(Enum):
+ """Event names for the SignalRouter"""
SERVER_EXCEPTION_REPORT = "server.exception.report"
SERVER_INIT_AFTER = "server.init.after"
@@ -83,10 +84,12 @@
class Signal(Route):
+ """A `Route` that is used to dispatch signals to handlers"""
@datacl... | https://raw.githubusercontent.com/sanic-org/sanic/HEAD/sanic/signals.py |
Document functions with detailed explanations | from __future__ import annotations
from ssl import SSLContext
from typing import TYPE_CHECKING
from sanic.config import Config
from sanic.exceptions import ServerError
from sanic.http.constants import HTTP
from sanic.http.tls import get_ssl_context
if TYPE_CHECKING:
from sanic.app import Sanic
import asyncio
i... | --- +++ @@ -59,6 +59,68 @@ asyncio_server_kwargs=None,
version=HTTP.VERSION_1,
):
+ """Start asynchronous HTTP Server on an individual process.
+
+ :param host: Address to host on
+ :param port: Port to host on
+ :param before_start: function to be executed before the server starts
+ ... | https://raw.githubusercontent.com/sanic-org/sanic/HEAD/sanic/server/runners.py |
Help me add docstrings to my project | from __future__ import annotations
from typing import Any
class RequestParameters(dict):
def get(self, name: str, default: Any | None = None) -> Any | None:
return super().get(name, [default])[0]
def getlist(
self, name: str, default: list[Any] | None = None
) -> list[Any]:
retu... | --- +++ @@ -4,11 +4,30 @@
class RequestParameters(dict):
+ """Hosts a dict with lists as values where get returns the first value of the list and getlist returns the whole shebang""" # noqa: E501
def get(self, name: str, default: Any | None = None) -> Any | None:
+ """Return the first value, eithe... | https://raw.githubusercontent.com/sanic-org/sanic/HEAD/sanic/request/parameters.py |
Generate missing documentation strings | from __future__ import annotations
from typing import TYPE_CHECKING
from sanic.exceptions import SanicException
if TYPE_CHECKING:
from sanic import Sanic
class AsyncioServer:
__slots__ = ("app", "connections", "loop", "serve_coro", "server")
def __init__(
self,
app: Sanic,
lo... | --- +++ @@ -10,6 +10,7 @@
class AsyncioServer:
+ """Wraps an asyncio server with functionality that might be useful to a user who needs to manage the server lifecycle manually.""" # noqa: E501
__slots__ = ("app", "connections", "loop", "serve_coro", "server")
@@ -29,30 +30,38 @@ self.server = N... | https://raw.githubusercontent.com/sanic-org/sanic/HEAD/sanic/server/async_server.py |
Add missing documentation to my Python functions | from typing import Dict, Optional, Type
from pydantic import BaseModel, Field
from kirara_ai.im.adapter import IMAdapter
class IMAdapterInfo(BaseModel):
name: str
config_class: Type[BaseModel] = Field(exclude=True)
adapter_class: Type[IMAdapter] = Field(exclude=True)
localized_name: Optional[str] =... | --- +++ @@ -6,6 +6,7 @@
class IMAdapterInfo(BaseModel):
+ """IM适配器信息"""
name: str
config_class: Type[BaseModel] = Field(exclude=True)
@@ -15,6 +16,9 @@ detail_info_markdown: Optional[str] = None
class IMRegistry:
+ """
+ 适配器注册表,用于动态注册和管理 adapter。
+ """
_registry: Dict[str, IMAd... | https://raw.githubusercontent.com/lss233/kirara-ai/HEAD/kirara_ai/im/im_registry.py |
Write beginner-friendly docstrings | import asyncio
from typing import Dict, Type
from pydantic import BaseModel
from kirara_ai.config.config_loader import pydantic_validation_wrapper
from kirara_ai.config.global_config import GlobalConfig, IMConfig
from kirara_ai.events.event_bus import EventBus
from kirara_ai.events.im import IMAdapterStarted, IMAdapt... | --- +++ @@ -17,6 +17,9 @@
class IMManager:
+ """
+ IM 生命周期管理器,负责管理所有 adapter 的启动、运行和停止。
+ """
container: DependencyContainer
@@ -41,26 +44,54 @@ self.adapters: Dict[str, IMAdapter] = {}
def get_adapter_type(self, name: str) -> str:
+ """
+ 获取指定名称的 adapter 类型。
+ ... | https://raw.githubusercontent.com/lss233/kirara-ai/HEAD/kirara_ai/im/manager.py |
Generate helpful docstrings for debugging | import os
import shutil
from functools import wraps
from typing import Optional, Type, TypeVar
from pydantic import BaseModel, ValidationError
from pydantic.json_schema import GenerateJsonSchema, JsonSchemaValue
from ruamel.yaml import YAML
from ..logger import get_logger
from . import DATA_PATH
CONFIG_FILE = os.pat... | --- +++ @@ -15,11 +15,20 @@ T = TypeVar("T", bound=BaseModel)
class ConfigLoader:
+ """
+ 配置文件加载器,支持加载和保存 YAML 文件,并保留注释。
+ """
yaml = YAML()
@staticmethod
def load_config(config_path: str, config_class: Type[T]) -> T:
+ """
+ 从 YAML 文件中加载配置,并将其序列化为相应的配置对象。
+ :param co... | https://raw.githubusercontent.com/lss233/kirara-ai/HEAD/kirara_ai/config/config_loader.py |
Document this code for team use | from logging.config import fileConfig
from alembic import context
from sqlalchemy import engine_from_config, pool
# this is the Alembic Config object, which provides
# access to the values within the .ini file in use.
config = context.config
# Interpret the config file for Python logging.
# This line sets up loggers... | --- +++ @@ -28,6 +28,17 @@
def run_migrations_offline() -> None:
+ """Run migrations in 'offline' mode.
+
+ This configures the context with just a URL
+ and not an Engine, though an Engine is acceptable
+ here as well. By skipping the Engine creation
+ we don't even need a DBAPI to be available.
+
... | https://raw.githubusercontent.com/lss233/kirara-ai/HEAD/kirara_ai/alembic/env.py |
Write docstrings describing each step | from abc import ABC, abstractmethod
from typing import Any, Optional, Protocol
from pydantic import BaseModel
from typing_extensions import runtime_checkable
from kirara_ai.im.message import IMMessage
from kirara_ai.im.sender import ChatSender
from kirara_ai.llm.llm_manager import LLMManager
from .profile import Use... | --- +++ @@ -12,29 +12,58 @@
class BotStatus(BaseModel):
+ """
+ 机器人状态
+ """
username: str
avatar_url: str
@runtime_checkable
class EditStateAdapter(Protocol):
+ """
+ 编辑状态适配器接口,定义了如何设置或取消对话的编辑状态
+ """
async def set_chat_editing_state(
self, chat_sender: ChatSender, ... | https://raw.githubusercontent.com/lss233/kirara-ai/HEAD/kirara_ai/im/adapter.py |
Add docstrings for production code | import asyncio
import json
import os
import re
import traceback
from collections import deque
from datetime import datetime
from typing import Any, Callable, Dict, List
from loguru import logger
# 创建 logs 文件夹
LOG_DIR = "logs"
if not os.path.exists(LOG_DIR):
os.makedirs(LOG_DIR)
# 配置日志格式和颜色
logger.remove() # 移除默... | --- +++ @@ -54,6 +54,7 @@ LogBroadcasterCallback = Callable[[Dict | List[Dict]], None]
# 通用日志处理器管理类
class LogBroadcaster:
+ """通用日志广播器,支持多种日志订阅方式"""
_instance = None
_subscribers: Dict[int, LogBroadcasterCallback] = {}
@@ -75,6 +76,7 @@ self._setup_log_handler()
def _setup_lo... | https://raw.githubusercontent.com/lss233/kirara-ai/HEAD/kirara_ai/logger.py |
Generate docstrings for each module | import json
from typing import Literal, Optional, Union
from pydantic import BaseModel, field_validator, model_validator
from typing_extensions import Self
from .tool import LLMToolResultContent
RoleType = Literal["system", "user", "assistant"]
class LLMChatTextContent(BaseModel):
type: Literal["text"] = "text"... | --- +++ @@ -17,6 +17,11 @@ media_id: str
class LLMToolCallContent(BaseModel):
+ """
+ 这是模型请求工具的消息内容,
+ 模型强相关内容,如果你 message 或者 memory 内包含了这个内容,请保证调用同一个 model
+ 此部分 role 应该归属于"assistant"
+ """
type: Literal["tool_call"] = "tool_call"
# call id,部分模型用此字段区分不同函数的调用,若没有返回则由 Adapter 生成
id: ... | https://raw.githubusercontent.com/lss233/kirara-ai/HEAD/kirara_ai/llm/format/message.py |
Create Google-style docstrings for my code | import contextvars
from typing import Any, Optional, Type, TypeVar, overload
T = TypeVar("T")
class DependencyContainer:
def __init__(self, parent=None):
self.parent = parent # 父容器,用于支持作用域嵌套
self.registry = {} # 当前容器的注册表
def register(self, key, value):
self.registry[key] = value
... | --- +++ @@ -4,11 +4,65 @@ T = TypeVar("T")
class DependencyContainer:
+ """
+ 依赖注入容器,提供注册和解析的功能。你可以在此获取一些全局的对象。
+ 基本用法:
+ ```python
+ # 1. 注册全局对象 - 通常在初始化时使用
+ container.register(YourObj, your_obj_instance)
+
+ # 2. 获取全局对象 - 在你的逻辑代码中使用
+ your_obj_instance = container.resolve(YourObj)
+
+ ... | https://raw.githubusercontent.com/lss233/kirara-ai/HEAD/kirara_ai/ioc/container.py |
Write docstrings including parameters and return values | from typing import Literal, Optional
from pydantic import BaseModel
from .message import LLMChatTextContent, LLMChatImageContent
from .response import Usage
FormatType = Literal["base64"]
OutputType = Literal["float", "int8", "uint8", "binary", "ubinary"]
InputType = Literal["string", "query", "document"]
InputUnionT... | --- +++ @@ -10,6 +10,20 @@ InputUnionType = LLMChatTextContent | LLMChatImageContent
class LLMEmbeddingRequest(BaseModel):
+ """
+ 此模型用于规范embedding请求的格式
+ Tips: 各大模型向量维度以及向量转化函数不同,因此当你用于向量数据库时,请确保存储和检索使用同一个模型,并确保模型向量一致(部分模型支持同一模型设置向量维度)
+ Note: 注意一下字段为混合字段, 部分字段在部分模型中不起作用, 请参照对应ap文档传递参数。
+
+ Attribute... | https://raw.githubusercontent.com/lss233/kirara-ai/HEAD/kirara_ai/llm/format/embedding.py |
Add docstrings for better understanding | from typing import Dict, Optional, Type
from pydantic import BaseModel
from kirara_ai.logger import get_logger
from .adapter import LLMBackendAdapter
from .model_types import LLMAbility # noqa: F401
class LLMBackendRegistry:
_adapters: Dict[str, Type[LLMBackendAdapter]]
_configs: Dict[str, Type[BaseModel... | --- +++ @@ -9,6 +9,9 @@
class LLMBackendRegistry:
+ """
+ LLM后端注册表
+ """
_adapters: Dict[str, Type[LLMBackendAdapter]]
_configs: Dict[str, Type[BaseModel]]
@@ -25,6 +28,12 @@ config_class: Type[BaseModel],
*args, **kwargs
):
+ """
+ 注册一个LLM后端适配器
+ :par... | https://raw.githubusercontent.com/lss233/kirara-ai/HEAD/kirara_ai/llm/llm_registry.py |
Document this code for team use | from typing import Optional
from typing_extensions import Self
from pydantic import BaseModel, model_validator
from .response import Usage
class LLMReRankRequest(BaseModel):
query: str
documents: list[str]
model: str
top_k: Optional[int] = None
return_documents: Optional[bool] = None
truncatio... | --- +++ @@ -5,6 +5,22 @@ from .response import Usage
class LLMReRankRequest(BaseModel):
+ """
+ ReRanker: 重排器是一个重要的处理方案, 通常见于 EsSearch 的优化方案中。
+ 本接口是适用于 LLM 的重排器的请求模型一般与嵌入式式模型组合使用提高向量搜索准确率。
+
+ 传入一系列原始文档和一个查询语句,返回器相似度数值。
+ Attributes:
+ query: 原始查询语句
+ documents: 文档列表, 包含文档的文本内容。每个文档转化为一... | https://raw.githubusercontent.com/lss233/kirara-ai/HEAD/kirara_ai/llm/format/rerank.py |
Generate consistent documentation across files | import random
from typing import Dict, List, Optional
from typing_extensions import deprecated
from kirara_ai.config.global_config import GlobalConfig, ModelConfig
from kirara_ai.events.event_bus import EventBus
from kirara_ai.events.llm import LLMAdapterLoaded, LLMAdapterUnloaded
from kirara_ai.ioc.container import ... | --- +++ @@ -15,6 +15,9 @@
class LLMManager:
+ """
+ 跟踪、管理和调度模型后端
+ """
container: DependencyContainer
config: GlobalConfig
@@ -41,6 +44,7 @@ self.backends: Dict[str, LLMBackendAdapter] = {}
def load_config(self):
+ """加载配置文件中的所有启用的后端"""
for backend in self.config.... | https://raw.githubusercontent.com/lss233/kirara-ai/HEAD/kirara_ai/llm/llm_manager.py |
Turn comments into proper docstrings | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import asyncio
from functools import partial
from typing import Dict, NamedTuple, Optional, Tuple
from mcp import McpError, types
from mcp.shared.session import RequestResponder
from kirara_ai.config.global_config import GlobalConfig, MCPServerConfig
from kirara_ai.ioc.c... | --- +++ @@ -17,13 +17,16 @@ logger = get_logger("MCP")
class ToolCacheEntry(NamedTuple):
+ """工具缓存条目"""
server_id: str # 服务器ID
original_name: str # 原始工具名称
tool_info: types.Tool # 工具信息
class MCPServerManager:
+ """MCP服务器管理器,负责管理和控制MCP服务器进程"""
def __init__(self, container:... | https://raw.githubusercontent.com/lss233/kirara-ai/HEAD/kirara_ai/mcp_module/manager.py |
Add docstrings including usage examples | from abc import abstractmethod
from enum import Enum
class ModelType(Enum):
LLM = "llm"
Embedding = "embedding"
ImageGeneration = "image_generation"
Audio = "audio"
# 可以根据需要添加更多类型
@classmethod
def from_str(cls, value: str) -> "ModelType":
return next(
(enum_value f... | --- +++ @@ -3,6 +3,9 @@
class ModelType(Enum):
+ """
+ 模型类型枚举
+ """
LLM = "llm"
Embedding = "embedding"
ImageGeneration = "image_generation"
@@ -11,6 +14,9 @@
@classmethod
def from_str(cls, value: str) -> "ModelType":
+ """
+ 从字符串转换为ModelType枚举
+ """
... | https://raw.githubusercontent.com/lss233/kirara-ai/HEAD/kirara_ai/llm/model_types.py |
Create structured documentation for my script | import json
from typing import Any, Callable, Coroutine, Generic, List, Literal, Optional, TypeVar, Union
from pydantic import BaseModel, ConfigDict, Field, field_serializer, field_validator
class TextContent(BaseModel):
type: Literal["text"] = "text"
text: str
class MediaContent(BaseModel):
type: Litera... | --- +++ @@ -16,6 +16,11 @@ ToolResponseTypes = List[Union[TextContent, MediaContent]]
class LLMToolResultContent(BaseModel):
+ """
+ 这是工具回应的消息内容,
+ 模型强相关内容,如果你 message 或者 memory 内包含了这个内容,请保证调用同一个 model
+ 此部分 role 应该对应 "tool"
+ """
type: Literal["tool_result"] = "tool_result"
# call id,对应 LLM... | https://raw.githubusercontent.com/lss233/kirara-ai/HEAD/kirara_ai/llm/format/tool.py |
Add inline docstrings for readability | import asyncio
from contextlib import AsyncExitStack
from typing import Optional
import anyio
import anyio.lowlevel
from mcp import ClientSession, StdioServerParameters, stdio_client, types
from mcp.client.session import MessageHandlerFnT
from mcp.client.sse import sse_client
from mcp.shared.session import RequestResp... | --- +++ @@ -17,10 +17,25 @@ logger = get_logger("MCP.Server")
class MCPServer:
+ """
+ MCP (Model Control Protocol) 服务器客户端类
+
+ 用于与 MCP 服务器进行通信,支持 stdio 和 SSE 两种连接模式。
+ 提供工具调用、补全、资源管理等功能。
+
+ 本类为 mcp.ClientSession 的代理,
+ 使其适应 Kirara AI 的生命周期。
+ """
session: Optional[ClientSession] =... | https://raw.githubusercontent.com/lss233/kirara-ai/HEAD/kirara_ai/mcp_module/server.py |
Add docstrings for internal functions | import io
import os
import platform
import shutil
import subprocess
import tarfile
import tempfile
import threading
import zipfile
from pathlib import Path
from typing import Awaitable, Callable, Optional, Tuple
import aiohttp
from kirara_ai.config.global_config import GlobalConfig
from kirara_ai.logger import get_lo... | --- +++ @@ -22,6 +22,7 @@
class FrpcManager:
+ """FRPC 管理器"""
def __init__(self, global_config: GlobalConfig):
self.global_config = global_config
@@ -50,6 +51,7 @@ self._get_frpc_version()
async def download_frpc(self, progress_callback: Optional[Callable[[float], Await... | https://raw.githubusercontent.com/lss233/kirara-ai/HEAD/kirara_ai/plugins/bundled_frpc/frpc_manager.py |
Add return value explanations in docstrings | import re
from typing import Dict, List, Optional, Tuple
class XMLHelper:
@staticmethod
def escape_xml_attr(text: str) -> str:
if not isinstance(text, str):
text = str(text)
return text.replace("&", "&").replace("\"", """).replace("<", "<").replace(">", ">")
@s... | --- +++ @@ -3,19 +3,23 @@
class XMLHelper:
+ """XML 格式化和解析的辅助工具类"""
@staticmethod
def escape_xml_attr(text: str) -> str:
+ """转义XML属性中的特殊字符"""
if not isinstance(text, str):
text = str(text)
return text.replace("&", "&").replace("\"", """).replace("<", "&... | https://raw.githubusercontent.com/lss233/kirara-ai/HEAD/kirara_ai/memory/composes/xml_helper.py |
Provide docstrings following PEP 257 | import asyncio
import base64
import functools
import uuid
from typing import List, Optional
import ymbotpy as botpy
import ymbotpy.message
from pydantic import BaseModel, ConfigDict, Field
from ymbotpy.http import Route as BotpyRoute
from ymbotpy.types.message import Media as BotpyMedia
from kirara_ai.im.adapter impo... | --- +++ @@ -35,6 +35,9 @@
class QQBotConfig(BaseModel):
+ """
+ QQBot 配置文件模型。
+ """
app_id: str = Field(description="机器人的 App ID。")
app_secret: str = Field(title="App Secret", description="机器人的 App Secret。")
token: str = Field(
@@ -56,6 +59,9 @@ openid: Optional[str] = None,
group_o... | https://raw.githubusercontent.com/lss233/kirara-ai/HEAD/kirara_ai/plugins/im_qqbot_adapter/adapter.py |
Add docstrings for utility scripts | import asyncio
import importlib
import os
import sys
from typing import Dict, List, Optional, Type
from kirara_ai.config.global_config import GlobalConfig
from kirara_ai.events.event_bus import EventBus
from kirara_ai.events.plugin import PluginLoaded, PluginStarted, PluginStopped
from kirara_ai.ioc.container import D... | --- +++ @@ -28,6 +28,7 @@ self.event_bus = self.container.resolve(EventBus)
def register_plugin(self, plugin_class: Type[Plugin], plugin_name: Optional[str] = None):
+ """注册一个插件类,主要用于测试"""
plugin = self.instantiate_plugin(plugin_class)
key = plugin_name or plugin_class.__name__
... | https://raw.githubusercontent.com/lss233/kirara-ai/HEAD/kirara_ai/plugin_manager/plugin_loader.py |
Include argument descriptions in docstrings | import asyncio
import random
from functools import lru_cache
from typing import List, Optional
from pydantic import BaseModel, ConfigDict, Field
from telegram import Bot, ChatFullInfo, Update, User
from telegram.constants import MessageEntityType
from telegram.ext import Application, CommandHandler, ContextTypes, Mess... | --- +++ @@ -28,6 +28,9 @@
class TelegramConfig(BaseModel):
+ """
+ Telegram 配置文件模型。
+ """
token: str = Field(description="Telegram 机器人的 Token,从 @BotFather 获取。")
model_config = ConfigDict(extra="allow")
@@ -37,6 +40,9 @@
class TelegramAdapter(IMAdapter, UserProfileAdapter, EditStateAdapter, ... | https://raw.githubusercontent.com/lss233/kirara-ai/HEAD/kirara_ai/plugins/im_telegram_adapter/adapter.py |
Add docstrings to improve collaboration | import uuid
from typing import Optional, Tuple
from kirara_ai.llm.format.message import LLMChatContentPartType, LLMToolCallContent
from kirara_ai.llm.format.tool import Function, ToolCall
from kirara_ai.llm.model_types import AudioModelAbility, EmbeddingModelAbility, ImageModelAbility, LLMAbility, ModelType
def gene... | --- +++ @@ -22,6 +22,10 @@ return None
def guess_openai_model(model_id: str) -> Tuple[ModelType, int] | None:
+ """
+ 根据模型ID猜测模型类型和能力
+ 返回: (ModelType, ability_bitmask) 或 None
+ """
model_id = model_id.lower()
# 1. 检查嵌入模型
@@ -120,6 +124,10 @@ return (ModelType.LLM, ability... | https://raw.githubusercontent.com/lss233/kirara-ai/HEAD/kirara_ai/plugins/llm_preset_adapters/utils.py |
Annotate my code with docstrings | import ast
import logging
from abc import ABC, abstractmethod
from typing import Dict, List, Optional
from lsprotocol.types import CodeAction, CodeActionParams, Diagnostic, DiagnosticSeverity, Position, Range
from pygls.server import LanguageServer
from pygls.workspace import Document
logger = logging.getLogger(__nam... | --- +++ @@ -11,6 +11,7 @@
class BaseDiagnostic(ABC):
+ """诊断检查器的抽象基类"""
SOURCE_NAME: str = "base-diagnostic" # 每个子类应覆盖此项
@@ -19,12 +20,34 @@
@abstractmethod
def check(self, doc: Document) -> List[Diagnostic]:
+ """
+ 对文档执行诊断检查。
+
+ Args:
+ doc: 要检查的文档对象。
+
+ ... | https://raw.githubusercontent.com/lss233/kirara-ai/HEAD/kirara_ai/web/api/block/diagnostics/base_diagnostic.py |
Document functions with detailed explanations | import logging
from typing import Any, List
from lsprotocol.types import (CodeAction, CodeActionKind, CodeActionParams, Diagnostic, DiagnosticSeverity, Position,
Range, TextEdit, WorkspaceEdit)
from pyflakes import api as pyflakes_api
from pyflakes import messages as pyflakes_messages
fro... | --- +++ @@ -127,6 +127,7 @@
class PyflakesDiagnostic(BaseDiagnostic):
+ """使用 Pyflakes 检查 Python 代码错误的诊断器 (增强版)"""
SOURCE_NAME: str = "pyflakes"
@@ -134,6 +135,9 @@ super().__init__(ls)
def check(self, doc: Document) -> List[Diagnostic]:
+ """
+ 对文档执行 Pyflakes 检查。
+ "... | https://raw.githubusercontent.com/lss233/kirara-ai/HEAD/kirara_ai/web/api/block/diagnostics/pyflakes_check.py |
Fully document this Python code with docstrings | import warnings
from inspect import Parameter, signature
from typing import Annotated, Dict, List, Optional, Tuple, Type, get_args, get_origin
from kirara_ai.workflow.core.block import Block
from kirara_ai.workflow.core.block.param import ParamMeta
from .schema import BlockConfig, BlockInput, BlockOutput
from .type_s... | --- +++ @@ -10,6 +10,9 @@
def extract_block_param(param: Parameter, type_system: TypeSystem) -> BlockConfig:
+ """
+ 提取 Block 参数信息,包括类型字符串、标签、是否必需、描述和默认值。
+ """
param_type = param.annotation
label = param.name
description = None
@@ -61,6 +64,7 @@
class BlockRegistry:
+ """Block 注册表,用于... | https://raw.githubusercontent.com/lss233/kirara-ai/HEAD/kirara_ai/workflow/core/block/registry.py |
Add standardized docstrings across the file | import asyncio
import functools
from collections import defaultdict
from concurrent.futures import ThreadPoolExecutor
from typing import Any, Dict, List
from kirara_ai.events.event_bus import EventBus
from kirara_ai.ioc.container import DependencyContainer
from kirara_ai.ioc.inject import Inject
from kirara_ai.logger ... | --- +++ @@ -19,6 +19,12 @@
@Inject()
def __init__(self, container: DependencyContainer, workflow: Workflow, registry: BlockRegistry, event_bus: EventBus):
+ """
+ 初始化 WorkflowExecutor 实例。
+
+ :param workflow: 要执行的工作流对象
+ :param registry: Block注册表,用于类型检查
+ """
s... | https://raw.githubusercontent.com/lss233/kirara-ai/HEAD/kirara_ai/workflow/core/execution/executor.py |
Write reusable docstrings | import importlib
import random
import string
import warnings
from dataclasses import dataclass, field
from typing import Any, Callable, Dict, List, Optional, Tuple, Type, Union
from ruamel.yaml import YAML
from kirara_ai.ioc.container import DependencyContainer
from kirara_ai.workflow.core.block import Block, Conditi... | --- +++ @@ -31,6 +31,7 @@
@dataclass
class BlockSpec:
+ """Block 规格的数据类,用于统一处理 block 的创建参数"""
block_class: Type[Block]
name: Optional[str] = None
@@ -82,6 +83,7 @@ self.position = position
def ancestors(self) -> List["Node"]:
+ """获取所有祖先节点"""
result: List["Node"] = []
... | https://raw.githubusercontent.com/lss233/kirara-ai/HEAD/kirara_ai/workflow/core/workflow/builder.py |
Write docstrings describing functionality | import asyncio
import json
import base64
import os
from typing import *
import httpx
from bs4 import BeautifulSoup as bs
from ghunt import globals as gb
from ghunt.objects.base import GHuntCreds
from ghunt.errors import *
from ghunt.helpers.utils import *
from ghunt.helpers import listener
from ghunt.helpers.knowledg... | --- +++ @@ -18,6 +18,12 @@
async def android_master_auth(as_client: httpx.AsyncClient, oauth_token: str) -> Tuple[str, List[str], str, str]:
+ """
+ Takes an oauth_token to perform an android authentication
+ to get the master token and other informations.
+
+ Returns the master token, conne... | https://raw.githubusercontent.com/mxrch/GHunt/HEAD/ghunt/helpers/auth.py |
Generate missing documentation strings | from ghunt.objects.base import GHuntCreds
from ghunt.errors import *
import ghunt.globals as gb
from ghunt.objects.apis import GAPI, EndpointConfig
from ghunt.parsers.mobilesdk import MobileSDKDynamicConfig
import httpx
from typing import *
import inspect
import json
class MobileSDKPaHttp(GAPI):
def __init__(se... | --- +++ @@ -28,6 +28,10 @@ self._load_api(creds, headers)
async def test_iam_permissions(self, as_client: httpx.AsyncClient, project_identifier: str, permissions: List[str]) -> Tuple[bool, List[str]]:
+ """
+ Returns the permissions you have against a project.
+ The project i... | https://raw.githubusercontent.com/mxrch/GHunt/HEAD/ghunt/apis/mobilesdk.py |
Write Python docstrings for this snippet | from typing import *
from ghunt.parsers.drive import DriveComment, DriveCommentList, DriveCommentReply, DriveFile
from ghunt.objects.base import DriveExtractedUser
from ghunt.helpers.utils import oprint # TEMP
def get_users_from_file(file: DriveFile) -> List[DriveExtractedUser]:
users: Dict[str, DriveExtrac... | --- +++ @@ -6,6 +6,10 @@
def get_users_from_file(file: DriveFile) -> List[DriveExtractedUser]:
+ """
+ Extracts the users from the permissions of a Drive file,
+ and the last modifying user.
+ """
users: Dict[str, DriveExtractedUser] = {}
for perms in [file.permissions, file.perm... | https://raw.githubusercontent.com/mxrch/GHunt/HEAD/ghunt/helpers/drive.py |
Write reusable docstrings | from dateutil.relativedelta import relativedelta
from datetime import datetime
import json
from geopy import distance
from geopy.geocoders import Nominatim
from typing import *
import httpx
from alive_progress import alive_bar
from ghunt import globals as gb
from ghunt.objects.base import *
from ghunt.helpers.utils i... | --- +++ @@ -16,6 +16,10 @@
def get_datetime(datepublished: str):
+ """
+ Get an approximative date from the maps review date
+ Examples : 'last 2 days', 'an hour ago', '3 years ago'
+ """
if datepublished.split()[0] in ["a", "an"]:
nb = 1
else:
@@ -42,6 +46,7 @@ return (da... | https://raw.githubusercontent.com/mxrch/GHunt/HEAD/ghunt/helpers/gmaps.py |
Add standardized docstrings across the file | from pathlib import Path
from PIL import Image
import hashlib
from typing import *
from time import time
from datetime import datetime, timezone
from dateutil.parser import isoparse
from copy import deepcopy
import jsonpickle
import json
from packaging.version import parse as parse_version
import httpx
import imagehas... | --- +++ @@ -20,6 +20,9 @@
def get_httpx_client() -> httpx.AsyncClient:
+ """
+ Returns a customized to better support the needs of GHunt CLI users.
+ """
return AsyncClient(http2=True, timeout=15)
# return AsyncClient(http2=True, timeout=15, proxies="http://127.0.0.1:8282", verify=False)
@@... | https://raw.githubusercontent.com/mxrch/GHunt/HEAD/ghunt/helpers/utils.py |
Add docstrings that explain inputs and outputs | from typing import *
from pathlib import Path
import json
from dateutil.relativedelta import relativedelta
from datetime import datetime
import base64
from autoslot import Slots
import httpx
from ghunt.errors import GHuntInvalidSession
# class SmartObj(Slots): # Not Python 3.13 compatible so FUCK it fr fr
# pas... | --- +++ @@ -23,6 +23,10 @@ self.authorization_tokens: Dict = {}
class GHuntCreds(SmartObj):
+ """
+ This object stores all the needed credentials that GHunt uses,
+ such as cookies, OSIDs, keys and tokens.
+ """
def __init__(self, creds_path: str = "") -> None:
self.co... | https://raw.githubusercontent.com/mxrch/GHunt/HEAD/ghunt/objects/base.py |
Document helper functions with docstrings | # Copyright 2026 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, s... | --- +++ @@ -75,6 +75,7 @@
def get_repository_maintainers(owner: str, repo: str) -> list[str]:
+ """Fetches all users with push/maintain access."""
url = f"https://api.github.com/repos/{owner}/{repo}/collaborators"
data = get_request(url, {"permission": "push"})
return [user["login"] for user in data]
@@ -... | https://raw.githubusercontent.com/google/adk-python/HEAD/contributing/samples/adk_issue_monitoring_agent/utils.py |
Generate missing documentation strings | #!/usr/bin/env python3
# Copyright 2026 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or ... | --- +++ @@ -13,6 +13,13 @@ # See the License for the specific language governing permissions and
# limitations under the License.
+"""
+build_llms_txt.py – produce llms.txt and llms-full.txt
+ – skips ```java``` blocks
+ – README can be next to docs/ or inside docs/
+ ... | https://raw.githubusercontent.com/google/adk-python/HEAD/contributing/dev/utils/build_llms_txt.py |
Add docstrings to improve readability | # Copyright 2026 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, s... | --- +++ @@ -12,6 +12,7 @@ # See the License for the specific language governing permissions and
# limitations under the License.
+"""Utility functions for cache analysis experiments."""
import asyncio
import time
@@ -25,6 +26,7 @@ async def call_agent_async(
runner: InMemoryRunner, user_id: str, session_id:... | https://raw.githubusercontent.com/google/adk-python/HEAD/contributing/samples/cache_analysis/utils.py |
Add standardized docstrings across the file | # Copyright 2026 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, s... | --- +++ @@ -31,6 +31,19 @@
def list_releases(repo_owner: str, repo_name: str) -> Dict[str, Any]:
+ """Lists all releases for a repository.
+
+ This function retrieves all releases and for each one, returns its ID,
+ creation time, publication time, and associated tag name. It handles
+ pagination to ensure all ... | https://raw.githubusercontent.com/google/adk-python/HEAD/contributing/samples/adk_documentation/tools.py |
Create documentation for each function signature | # Copyright 2026 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, s... | --- +++ @@ -38,6 +38,20 @@
async def process_single_issue(issue_number: int) -> Tuple[float, int]:
+ """
+ Processes a single GitHub issue using the AI agent and logs execution metrics.
+
+ Args:
+ issue_number (int): The GitHub issue number to audit.
+
+ Returns:
+ Tuple[float, int]: A tuple containi... | https://raw.githubusercontent.com/google/adk-python/HEAD/contributing/samples/adk_stale_agent/main.py |
Expand my code with proper documentation strings | # Copyright 2026 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, s... | --- +++ @@ -39,6 +39,7 @@ headers: dict[str, Any] | None = None,
params: dict[str, Any] | None = None,
) -> Dict[str, Any]:
+ """Executes a GET request."""
if headers is None:
headers = HEADERS
if params is None:
@@ -51,6 +52,7 @@ def get_paginated_request(
url: str, headers: dict[str, Any] |... | https://raw.githubusercontent.com/google/adk-python/HEAD/contributing/samples/adk_documentation/utils.py |
Add docstrings for internal functions | # Copyright 2026 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, s... | --- +++ @@ -18,17 +18,24 @@
class HotelBooker:
+ """
+ Core business logic for hotel booking, independent of any web framework.
+ """
def __init__(self, db_name="data.db"):
self.db_name = db_name
self._initialize_db()
def _get_db_connection(self):
+ """Helper to get a new, independent data... | https://raw.githubusercontent.com/google/adk-python/HEAD/contributing/samples/authn-adk-all-in-one/hotel_booker_app/hotelbooker_core.py |
Add professional docstrings to my codebase | # Copyright 2026 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, s... | --- +++ @@ -36,6 +36,7 @@
def run_graphql_query(query: str, variables: dict[str, Any]) -> dict[str, Any]:
+ """Executes a GraphQL query."""
payload = {"query": query, "variables": variables}
response = requests.post(
GITHUB_GRAPHQL_URL, headers=headers, json=payload, timeout=60
@@ -45,6 +46,7 @@
d... | https://raw.githubusercontent.com/google/adk-python/HEAD/contributing/samples/adk_answering_agent/utils.py |
Document functions with detailed explanations |
# Copyright 2026 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... | --- +++ @@ -1,3 +1,4 @@+"""ADK Answering Agent main script."""
# Copyright 2026 Google LLC
#
@@ -40,6 +41,14 @@ async def list_most_recent_discussions(
count: int = 1,
) -> Union[list[int], None]:
+ """Fetches a specified number of the most recently updated discussions.
+
+ Args:
+ count: The number of... | https://raw.githubusercontent.com/google/adk-python/HEAD/contributing/samples/adk_answering_agent/main.py |
Write docstrings describing each step | # Copyright 2026 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, s... | --- +++ @@ -56,6 +56,22 @@
def _get_cached_maintainers() -> List[str]:
+ """
+ Fetches the list of repository maintainers.
+
+ This function relies on `utils.get_request` for network resilience.
+ `get_request` is configured with an HTTPAdapter that automatically performs
+ exponential backoff retries (up to 6... | https://raw.githubusercontent.com/google/adk-python/HEAD/contributing/samples/adk_stale_agent/agent.py |
Create docstrings for API functions | # Copyright 2026 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... | --- +++ @@ -12,12 +12,14 @@ # See the License for the specific language governing permissions and
# limitations under the License.
+"""A Python coding agent using the GkeCodeExecutor for secure execution."""
from google.adk.agents import LlmAgent
from google.adk.code_executors import GkeCodeExecutor
def gke... | https://raw.githubusercontent.com/google/adk-python/HEAD/contributing/samples/code_execution/gke_sandbox_agent.py |
Generate docstrings with examples | # Copyright 2026 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, s... | --- +++ @@ -25,6 +25,14 @@
def get_discussion_and_comments(discussion_number: int) -> dict[str, Any]:
+ """Fetches a discussion and its comments using the GitHub GraphQL API.
+
+ Args:
+ discussion_number: The number of the GitHub discussion.
+
+ Returns:
+ A dictionary with the request status and the ... | https://raw.githubusercontent.com/google/adk-python/HEAD/contributing/samples/adk_answering_agent/tools.py |
Generate missing documentation strings | # Copyright 2026 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, s... | --- +++ @@ -55,6 +55,14 @@
def get_pull_request_details(pr_number: int) -> str:
+ """Get the details of the specified pull request.
+
+ Args:
+ pr_number: number of the GitHub pull request.
+
+ Returns:
+ The status of this request, with the details when successful.
+ """
print(f"Fetching details for P... | https://raw.githubusercontent.com/google/adk-python/HEAD/contributing/samples/adk_pr_triaging_agent/agent.py |
Help me document legacy Python code | # Copyright 2026 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, s... | --- +++ @@ -12,6 +12,11 @@ # See the License for the specific language governing permissions and
# limitations under the License.
+"""Cache Analysis Research Assistant Agent.
+
+This agent is designed to test ADK context caching features with a large prompt
+that exceeds 2048 tokens to meet both implicit and explici... | https://raw.githubusercontent.com/google/adk-python/HEAD/contributing/samples/cache_analysis/agent.py |
Write Python docstrings for this snippet | # Copyright 2026 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, s... | --- +++ @@ -34,6 +34,7 @@
def run_graphql_query(query: str, variables: dict[str, Any]) -> dict[str, Any]:
+ """Executes a GraphQL query."""
payload = {"query": query, "variables": variables}
response = requests.post(
GITHUB_GRAPHQL_URL, headers=headers, json=payload, timeout=60
@@ -43,6 +44,7 @@
d... | https://raw.githubusercontent.com/google/adk-python/HEAD/contributing/samples/adk_pr_triaging_agent/utils.py |
Help me document legacy Python code | # Copyright 2026 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, s... | --- +++ @@ -32,6 +32,7 @@
def cleanup_gcs_prefix(project_id: str, bucket_name: str, prefix: str) -> bool:
+ """Delete all the objects with the given prefix in the bucket."""
print(f"Start cleaning up GCS: gs://{bucket_name}/{prefix}...")
try:
storage_client = storage.Client(project=project_id)
@@ -53,6 ... | https://raw.githubusercontent.com/google/adk-python/HEAD/contributing/samples/adk_answering_agent/upload_docs_to_vertex_ai_search.py |
Add structured docstrings to improve clarity | # Copyright 2026 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, s... | --- +++ @@ -21,6 +21,14 @@
def roll_die(sides: int, tool_context: ToolContext) -> int:
+ """Roll a die and return the rolled result.
+
+ Args:
+ sides: The integer number of sides the die has.
+ tool_context: the tool context
+ Returns:
+ An integer of the result of rolling the die.
+ """
result = r... | https://raw.githubusercontent.com/google/adk-python/HEAD/contributing/samples/a2a_root/remote_a2a/hello_world/agent.py |
Add docstrings to existing functions | # Copyright 2026 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, s... | --- +++ @@ -12,6 +12,22 @@ # See the License for the specific language governing permissions and
# limitations under the License.
+"""ADK Release Analyzer Agent - Multi-agent architecture for analyzing releases.
+
+This agent uses a SequentialAgent + LoopAgent pattern to handle large releases
+without context overfl... | https://raw.githubusercontent.com/google/adk-python/HEAD/contributing/samples/adk_documentation/adk_release_analyzer/agent.py |
Write docstrings for utility functions | # Copyright 2026 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, s... | --- +++ @@ -84,6 +84,19 @@
def list_untriaged_issues(issue_count: int) -> dict[str, Any]:
+ """List open issues that need triaging.
+
+ Returns issues that need any of the following actions:
+ 1. Issues without component labels (need labeling + type setting)
+ 2. Issues with 'planned' label but no assignee (nee... | https://raw.githubusercontent.com/google/adk-python/HEAD/contributing/samples/adk_triaging_agent/agent.py |
Write docstrings describing functionality | # Copyright 2026 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, s... | --- +++ @@ -43,6 +43,7 @@
def get_oidc_config():
+ """Fetches and caches the OIDC configuration."""
global oidc_config
if oidc_config is None:
try:
@@ -55,6 +56,7 @@
def get_jwks():
+ """Fetches and caches the JSON Web Key Set (JWKS)."""
global jwks
if jwks is None:
config, error = get_o... | https://raw.githubusercontent.com/google/adk-python/HEAD/contributing/samples/authn-adk-all-in-one/hotel_booker_app/main.py |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.