instruction
stringclasses
100 values
code
stringlengths
78
193k
response
stringlengths
259
170k
file
stringlengths
59
203
Add docstrings to incomplete code
import asyncio import glob import os from pathlib import Path from .base import Tool class FileReadTool(Tool): def __init__(self): super().__init__( name="file_read", description=""" Read files or list directory contents. Operations: - read: ...
--- +++ @@ -1,3 +1,4 @@+"""File operation tools for reading and writing files.""" import asyncio import glob @@ -8,6 +9,7 @@ class FileReadTool(Tool): + """Tool for reading files and listing directories.""" def __init__(self): super().__init__( @@ -51,6 +53,17 @@ max_lines: int = 0, ...
https://raw.githubusercontent.com/anthropics/claude-quickstarts/HEAD/agents/tools/file_tools.py
Replace inline comments with docstrings
import asyncio from typing import Any async def _execute_single_tool( call: Any, tool_dict: dict[str, Any] ) -> dict[str, Any]: response = {"type": "tool_result", "tool_use_id": call.id} try: # Execute the tool directly result = await tool_dict[call.name].execute(**call.input) re...
--- +++ @@ -1,3 +1,4 @@+"""Tool execution utility with parallel execution support.""" import asyncio from typing import Any @@ -6,6 +7,7 @@ async def _execute_single_tool( call: Any, tool_dict: dict[str, Any] ) -> dict[str, Any]: + """Execute a single tool and handle errors.""" response = {"type": "to...
https://raw.githubusercontent.com/anthropics/claude-quickstarts/HEAD/agents/utils/tool_util.py
Add docstrings to improve code quality
from .base import Tool class ThinkTool(Tool): def __init__(self): super().__init__( name="think", description=( "Use the tool to think about something. It will not obtain " "new information or change the database, but just append the " ...
--- +++ @@ -1,8 +1,10 @@+"""Think tool for internal reasoning.""" from .base import Tool class ThinkTool(Tool): + """Tool for internal reasoning without executing external actions.""" def __init__(self): super().__init__( @@ -26,4 +28,5 @@ ) async def execute(self, thought: str...
https://raw.githubusercontent.com/anthropics/claude-quickstarts/HEAD/agents/tools/think.py
Generate docstrings with examples
#!/usr/bin/env python3 # stdlib from argparse import ArgumentParser from base64 import b64encode from pathlib import Path import json import logging import sys # dependencies from jinja2 import Environment, FileSystemLoader # local from .utils import Icon current_dir = Path(__file__).absolute().parent tpl = Environm...
--- +++ @@ -1,4 +1,5 @@ #!/usr/bin/env python3 +"""Super Tiny Icons Atlas generator""" # stdlib from argparse import ArgumentParser from base64 import b64encode @@ -44,6 +45,7 @@ fp.write(template.render(library=self.lib)) def parse_args(): + """parse arguments, initialize logging""" parser = Argu...
https://raw.githubusercontent.com/edent/SuperTinyIcons/HEAD/src/sti/atlas.py
Add docstrings for production code
# stdlib from argparse import ArgumentParser from pathlib import Path import logging import sys # dependencies from jinja2 import Environment, FileSystemLoader # local from .atlas import Atlas from .utils import get_icons_from, get_refs_from def parse_args(): parser = ArgumentParser(description=__doc__.splitli...
--- +++ @@ -1,3 +1,4 @@+"""Super Tiny Icons command line interface""" # stdlib from argparse import ArgumentParser @@ -14,6 +15,7 @@ def parse_args(): + """parse arguments, initialize logging""" parser = ArgumentParser(description=__doc__.splitlines()[0]) parser.add_argument( "-q", @@ -73,...
https://raw.githubusercontent.com/edent/SuperTinyIcons/HEAD/src/sti/cli.py
Write docstrings for data processing functions
# encoding=utf8 # 短信测压主程序 from utils import default_header_user_agent from utils.log import logger from utils.models import API from utils.req import reqFunc, reqFuncByProxy, runAsync from concurrent.futures import ThreadPoolExecutor from typing import List, Union import asyncio import json import pathlib import sys i...
--- +++ @@ -24,6 +24,9 @@ def load_proxies() -> list: + """load proxies for files + :return: proxies list + """ proxy_all = [] proxy_file = ["http_proxy.txt", "socks5_proxy.txt", "socks4_proxy.txt"] for fn in proxy_file: @@ -52,6 +55,9 @@ def load_json() -> List[API]: + """load json f...
https://raw.githubusercontent.com/OpenEthan/SMSBoom/HEAD/smsboom.py
Add docstrings to improve collaboration
import base64, hmac, json, secrets from datetime import timedelta from expiringdict import ExpiringDict import utils from mailconfig import get_mail_password, get_mail_user_privileges from mfa import get_hash_mfa_state, validate_auth_mfa DEFAULT_KEY_PATH = '/var/lib/mailinabox/api.key' DEFAULT_AUTH_REALM = 'Mail-i...
--- +++ @@ -20,11 +20,18 @@ self.sessions = ExpiringDict(max_len=64, max_age_seconds=self.max_session_duration.total_seconds()) def init_system_api_key(self): + """Write an API key to a local file so local processes can use the API""" with open(self.key_path, encoding='utf-8') as file: self.key = file.r...
https://raw.githubusercontent.com/mail-in-a-box/mailinabox/HEAD/management/auth.py
Add verbose docstrings with examples
#!/usr/local/lib/mailinabox/env/bin/python import argparse import datetime import gzip import os.path import re import shutil import tempfile import textwrap from collections import defaultdict, OrderedDict import dateutil.parser import time from dateutil.relativedelta import relativedelta import utils LOG_FILES =...
--- +++ @@ -61,6 +61,7 @@ def scan_files(collector): + """ Scan files until they run out or the earliest date is reached """ stop_scan = False @@ -90,6 +91,14 @@ def scan_mail_log(env): + """ Scan the system's mail log files and collect interesting data + + This function scans the 2 most recen...
https://raw.githubusercontent.com/mail-in-a-box/mailinabox/HEAD/management/mail_log.py
Document this module using docstrings
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved import os import contextlib import copy import numpy as np import torch from pycocotools.cocoeval import COCOeval from pycocotools.coco import COCO import pycocotools.mask as mask_util from util.misc import all_gather class CocoEvaluator(object)...
--- +++ @@ -1,4 +1,11 @@ # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved +""" +COCO evaluator that works in distributed mode. + +Mostly copy-paste from https://github.com/pytorch/vision/blob/edfd5a7/references/detection/coco_eval.py +The difference is that there is less copy-pasting from pycocoto...
https://raw.githubusercontent.com/facebookresearch/detr/HEAD/datasets/coco_eval.py
Document functions with detailed explanations
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved import torch from scipy.optimize import linear_sum_assignment from torch import nn from util.box_ops import box_cxcywh_to_xyxy, generalized_box_iou class HungarianMatcher(nn.Module): def __init__(self, cost_class: float = 1, cost_bbox: float...
--- +++ @@ -1,4 +1,7 @@ # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved +""" +Modules to compute the matching cost and solve the corresponding LSAP. +""" import torch from scipy.optimize import linear_sum_assignment from torch import nn @@ -7,8 +10,21 @@ class HungarianMatcher(nn.Module): ...
https://raw.githubusercontent.com/facebookresearch/detr/HEAD/models/matcher.py
Write Python docstrings for this snippet
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved import io from collections import defaultdict from typing import List, Optional import torch import torch.nn as nn import torch.nn.functional as F from torch import Tensor from PIL import Image import util.box_ops as box_ops from util.misc import ...
--- +++ @@ -1,4 +1,7 @@ # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved +""" +This file provides the definition of the convolutional heads used to predict masks, as well as the losses +""" import io from collections import defaultdict from typing import List, Optional @@ -64,6 +67,10 @@ cl...
https://raw.githubusercontent.com/facebookresearch/detr/HEAD/models/segmentation.py
Document this code for team use
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved import torch from models.backbone import Backbone, Joiner from models.detr import DETR, PostProcess from models.position_encoding import PositionEmbeddingSine from models.segmentation import DETRsegm, PostProcessPanoptic from models.transformer imp...
--- +++ @@ -24,6 +24,11 @@ def detr_resnet50(pretrained=False, num_classes=91, return_postprocessor=False): + """ + DETR R50 with 6 encoder and 6 decoder layers. + + Achieves 42/62.4 AP/AP50 on COCO val5k. + """ model = _make_detr("resnet50", dilation=False, num_classes=num_classes) if pretrai...
https://raw.githubusercontent.com/facebookresearch/detr/HEAD/hubconf.py
Generate docstrings with parameter types
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved import math import torch from torch import nn from util.misc import NestedTensor class PositionEmbeddingSine(nn.Module): def __init__(self, num_pos_feats=64, temperature=10000, normalize=False, scale=None): super().__init__() ...
--- +++ @@ -1,4 +1,7 @@ # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved +""" +Various positional encodings for the transformer. +""" import math import torch from torch import nn @@ -7,6 +10,10 @@ class PositionEmbeddingSine(nn.Module): + """ + This is a more standard version of the ...
https://raw.githubusercontent.com/facebookresearch/detr/HEAD/models/position_encoding.py
Create structured documentation for my script
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved import torch from torchvision.ops.boxes import box_area def box_cxcywh_to_xyxy(x): x_c, y_c, w, h = x.unbind(-1) b = [(x_c - 0.5 * w), (y_c - 0.5 * h), (x_c + 0.5 * w), (y_c + 0.5 * h)] return torch.stack(b, dim=-1) def box_...
--- +++ @@ -1,4 +1,7 @@ # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved +""" +Utilities for bounding box manipulation and GIoU. +""" import torch from torchvision.ops.boxes import box_area @@ -35,6 +38,14 @@ def generalized_box_iou(boxes1, boxes2): + """ + Generalized IoU from https...
https://raw.githubusercontent.com/facebookresearch/detr/HEAD/util/box_ops.py
Create docstrings for all classes and functions
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved import logging import math from typing import List import numpy as np import torch import torch.distributed as dist import torch.nn.functional as F from scipy.optimize import linear_sum_assignment from torch import nn from detectron2.layers import...
--- +++ @@ -29,6 +29,7 @@ class MaskedBackbone(nn.Module): + """ This is a thin wrapper around D2's backbone to provide padding masking""" def __init__(self, cfg): super().__init__() @@ -67,6 +68,9 @@ @META_ARCH_REGISTRY.register() class Detr(nn.Module): + """ + Implement Detr + """ ...
https://raw.githubusercontent.com/facebookresearch/detr/HEAD/d2/detr/detr.py
Provide clean and structured docstrings
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved import os import subprocess import time from collections import defaultdict, deque import datetime import pickle from packaging import version from typing import Optional, List import torch import torch.distributed as dist from torch import Tensor ...
--- +++ @@ -1,4 +1,9 @@ # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved +""" +Misc functions, including distributed helpers. + +Mostly copy-paste from torchvision references. +""" import os import subprocess import time @@ -20,6 +25,9 @@ class SmoothedValue(object): + """Track a series ...
https://raw.githubusercontent.com/facebookresearch/detr/HEAD/util/misc.py
Write docstrings for utility functions
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved import copy from typing import Optional, List import torch import torch.nn.functional as F from torch import nn, Tensor class Transformer(nn.Module): def __init__(self, d_model=512, nhead=8, num_encoder_layers=6, num_decoder...
--- +++ @@ -1,4 +1,12 @@ # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved +""" +DETR Transformer class. + +Copy-paste from torch.nn.Transformer with modifications: + * positional encodings are passed in MHattention + * extra LN at the end of encoder is removed + * decoder returns a stack ...
https://raw.githubusercontent.com/facebookresearch/detr/HEAD/models/transformer.py
Create docstrings for each class method
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved from collections import OrderedDict import torch import torch.nn.functional as F import torchvision from torch import nn from torchvision.models._utils import IntermediateLayerGetter from typing import Dict, List from util.misc import NestedTensor...
--- +++ @@ -1,4 +1,7 @@ # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved +""" +Backbone modules. +""" from collections import OrderedDict import torch @@ -14,6 +17,13 @@ class FrozenBatchNorm2d(torch.nn.Module): + """ + BatchNorm2d where the batch statistics and the affine parameters...
https://raw.githubusercontent.com/facebookresearch/detr/HEAD/models/backbone.py
Write documentation strings for class attributes
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved import random import PIL import torch import torchvision.transforms as T import torchvision.transforms.functional as F from util.box_ops import box_xyxy_to_cxcywh from util.misc import interpolate def crop(image, target, region): cropped_ima...
--- +++ @@ -1,4 +1,7 @@ # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved +""" +Transforms and data augmentation for both image + bbox. +""" import random import PIL @@ -207,6 +210,10 @@ class RandomSelect(object): + """ + Randomly selects between transforms1 and transforms2, + wit...
https://raw.githubusercontent.com/facebookresearch/detr/HEAD/datasets/transforms.py
Add docstrings to my Python code
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved import copy import logging import numpy as np import torch from detectron2.data import detection_utils as utils from detectron2.data import transforms as T from detectron2.data.transforms import TransformGen __all__ = ["DetrDatasetMapper"] def ...
--- +++ @@ -13,6 +13,11 @@ def build_transform_gen(cfg, is_train): + """ + Create a list of :class:`TransformGen` from config. + Returns: + list[TransformGen] + """ if is_train: min_size = cfg.INPUT.MIN_SIZE_TRAIN max_size = cfg.INPUT.MAX_SIZE_TRAIN @@ -35,6 +40,17 @@ c...
https://raw.githubusercontent.com/facebookresearch/detr/HEAD/d2/detr/dataset_mapper.py
Document all public functions with docstrings
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved import os import sys import itertools # fmt: off sys.path.insert(1, os.path.join(sys.path[0], '..')) # fmt: on import time from typing import Any, Dict, List, Set import torch import detectron2.utils.comm as comm from d2.detr import DetrDatasetM...
--- +++ @@ -1,4 +1,9 @@ # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved +""" +DETR Training Script. + +This script is a simplified version of the training script in detectron2/tools. +""" import os import sys import itertools @@ -24,9 +29,18 @@ class Trainer(DefaultTrainer): + """ + ...
https://raw.githubusercontent.com/facebookresearch/detr/HEAD/d2/train_net.py
Add docstrings to my Python code
import torch import pandas as pd import numpy as np import seaborn as sns import matplotlib.pyplot as plt from pathlib import Path, PurePath def plot_logs(logs, fields=('class_error', 'loss_bbox_unscaled', 'mAP'), ewm_col=0, log_name='log.txt'): func_name = "plot_utils.py::plot_logs" # verify logs is a list...
--- +++ @@ -1,3 +1,6 @@+""" +Plotting utilities to visualize training logs. +""" import torch import pandas as pd import numpy as np @@ -8,6 +11,18 @@ def plot_logs(logs, fields=('class_error', 'loss_bbox_unscaled', 'mAP'), ewm_col=0, log_name='log.txt'): + ''' + Function to plot specific fields from train...
https://raw.githubusercontent.com/facebookresearch/detr/HEAD/util/plot_utils.py
Please document this code using docstrings
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved import torch import torch.nn.functional as F from torch import nn from util import box_ops from util.misc import (NestedTensor, nested_tensor_from_tensor_list, accuracy, get_world_size, interpolate, is_...
--- +++ @@ -1,4 +1,7 @@ # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved +""" +DETR model and criterion classes. +""" import torch import torch.nn.functional as F from torch import nn @@ -16,7 +19,17 @@ class DETR(nn.Module): + """ This is the DETR module that performs object detection "...
https://raw.githubusercontent.com/facebookresearch/detr/HEAD/models/detr.py
Document helper functions with docstrings
import os from . import utils from .mackup import Mackup class ApplicationProfile: def __init__( self, mackup: Mackup, files: set[str], dry_run: bool, verbose: bool, ) -> None: assert isinstance(mackup, Mackup) assert isinstance(files, set) self.mackup: Mackup = mackup ...
--- +++ @@ -1,3 +1,9 @@+""" +Application Profile. + +An Application Profile contains all the information about an application in +Mackup. Name, files, ... +""" import os @@ -6,10 +12,18 @@ class ApplicationProfile: + """Instantiate this class with application specific data.""" def __init__( ...
https://raw.githubusercontent.com/lra/mackup/HEAD/src/mackup/application.py
Insert docstrings into my code
import configparser import os from typing import Union from .constants import APPS_DIR, CUSTOM_APPS_DIR, CUSTOM_APPS_DIR_XDG class ApplicationsDatabase: def __init__(self) -> None: # Build the dict that will contain the properties of each application self.apps: dict[str, dict[str, Union[str, se...
--- +++ @@ -1,3 +1,9 @@+""" +The applications database. + +The Applications Database provides an easy to use interface to load application +data from the Mackup Database (files). +""" import configparser import os @@ -7,8 +13,10 @@ class ApplicationsDatabase: + """Database containing all the configured appli...
https://raw.githubusercontent.com/lra/mackup/HEAD/src/mackup/appsdb.py
Create simple docstrings for beginners
import os import os.path import shutil import tempfile from typing import Optional from . import appsdb, config, utils class Mackup: def __init__(self, config_file: Optional[str] = None) -> None: self._config: config.Config = config.Config(config_file) self.mackup_folder: str = self._config.fu...
--- +++ @@ -1,3 +1,10 @@+""" +The Mackup Class. + +The Mackup class is keeping all the state that Mackup needs to keep during its +runtime. It also provides easy to use interface that is used by the Mackup UI. +The only UI for now is the command line. +""" import os import os.path @@ -9,14 +16,17 @@ class Macku...
https://raw.githubusercontent.com/lra/mackup/HEAD/src/mackup/mackup.py
Add clean documentation to messy code
import configparser import os import os.path from pathlib import Path from typing import Optional from .constants import ( CUSTOM_APPS_DIR, CUSTOM_APPS_DIR_XDG, ENGINE_DROPBOX, ENGINE_FS, ENGINE_GDRIVE, ENGINE_ICLOUD, MACKUP_BACKUP_PATH, MACKUP_CONFIG_FILE, ) from .utils import ( e...
--- +++ @@ -1,3 +1,4 @@+"""Package used to manage the .mackup.cfg config file.""" import configparser import os @@ -24,8 +25,16 @@ class Config: + """The Mackup Config class.""" def __init__(self, filename: Optional[str] = None) -> None: + """ + Create a Config instance. + + Args:...
https://raw.githubusercontent.com/lra/mackup/HEAD/src/mackup/config.py
Create docstrings for reusable components
import base64 import binascii import os import platform import shutil import sqlite3 import stat import subprocess import sys from typing import NoReturn, Optional from . import constants # Flag that controls how user confirmation works. # If True, the user wants to say "yes" to everything. FORCE_YES: bool = False #...
--- +++ @@ -1,3 +1,4 @@+"""System static utilities being used by the modules.""" import base64 import binascii @@ -23,6 +24,15 @@ def confirm(question: str) -> bool: + """ + Ask the user if he really wants something to happen. + + Args: + question(str): What can happen + + Returns: + (...
https://raw.githubusercontent.com/lra/mackup/HEAD/src/mackup/utils.py
Add docstrings to improve collaboration
from __future__ import annotations import ipaddress import re import typing import idna from ._exceptions import InvalidURL MAX_URL_LENGTH = 65536 # https://datatracker.ietf.org/doc/html/rfc3986.html#section-2.3 UNRESERVED_CHARACTERS = ( "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~" ) S...
--- +++ @@ -1,3 +1,20 @@+""" +An implementation of `urlparse` that provides URL validation and normalization +as described by RFC3986. + +We rely on this implementation rather than the one in Python's stdlib, because: + +* It provides more complete URL validation. +* It properly differentiates between an empty querystr...
https://raw.githubusercontent.com/encode/httpx/HEAD/httpx/_urlparse.py
Create structured documentation for my script
from __future__ import annotations import os import typing from ._models import Headers from ._types import CertTypes, HeaderTypes, TimeoutTypes from ._urls import URL if typing.TYPE_CHECKING: import ssl # pragma: no cover __all__ = ["Limits", "Proxy", "Timeout", "create_ssl_context"] class UnsetType: pa...
--- +++ @@ -70,6 +70,18 @@ class Timeout: + """ + Timeout configuration. + + **Usage**: + + Timeout(None) # No timeouts. + Timeout(5.0) # 5s timeout on all operations. + Timeout(None, connect=5.0) # 5s timeout on connect, no other timeouts. + Timeout(5.0, connect=1...
https://raw.githubusercontent.com/encode/httpx/HEAD/httpx/_config.py
Add standardized docstrings across the file
from __future__ import annotations import datetime import enum import logging import time import typing import warnings from contextlib import asynccontextmanager, contextmanager from types import TracebackType from .__version__ import __version__ from ._auth import Auth, BasicAuth, FunctionAuth from ._config import ...
--- +++ @@ -60,6 +60,9 @@ def _is_https_redirect(url: URL, location: URL) -> bool: + """ + Return 'True' if 'location' is a HTTPS upgrade of 'url' + """ if url.host != location.host: return False @@ -78,6 +81,9 @@ def _same_origin(url: URL, other: URL) -> bool: + """ + Return 'Tru...
https://raw.githubusercontent.com/encode/httpx/HEAD/httpx/_client.py
Write docstrings describing each step
from __future__ import annotations import typing from contextlib import contextmanager from ._client import Client from ._config import DEFAULT_TIMEOUT_CONFIG from ._models import Response from ._types import ( AuthTypes, CookieTypes, HeaderTypes, ProxyTypes, QueryParamTypes, RequestContent, ...
--- +++ @@ -54,6 +54,51 @@ verify: ssl.SSLContext | str | bool = True, trust_env: bool = True, ) -> Response: + """ + Sends an HTTP request. + + **Parameters:** + + * **method** - HTTP method for the new `Request` object: `GET`, `OPTIONS`, + `HEAD`, `POST`, `PUT`, `PATCH`, or `DELETE`. + * *...
https://raw.githubusercontent.com/encode/httpx/HEAD/httpx/_api.py
Please document this code using docstrings
from http.cookiejar import CookieJar from typing import ( IO, TYPE_CHECKING, Any, AsyncIterable, AsyncIterator, Callable, Dict, Iterable, Iterator, List, Mapping, Optional, Sequence, Tuple, Union, ) if TYPE_CHECKING: # pragma: no cover from ._auth impor...
--- +++ @@ -1,3 +1,6 @@+""" +Type definitions for type checking purposes. +""" from http.cookiejar import CookieJar from typing import ( @@ -94,6 +97,10 @@ yield b"" # pragma: no cover def close(self) -> None: + """ + Subclasses can override this method to release any network resources...
https://raw.githubusercontent.com/encode/httpx/HEAD/httpx/_types.py
Write docstrings for data processing functions
from __future__ import annotations import ipaddress import os import re import typing from urllib.request import getproxies from ._types import PrimitiveData if typing.TYPE_CHECKING: # pragma: no cover from ._urls import URL def primitive_value_to_str(value: PrimitiveData) -> str: if value is True: ...
--- +++ @@ -13,6 +13,11 @@ def primitive_value_to_str(value: PrimitiveData) -> str: + """ + Coerce a primitive data type into a string value. + + Note that we prefer JSON-style 'true'/'false' for boolean values here. + """ if value is True: return "true" elif value is False: @@ -23,6 ...
https://raw.githubusercontent.com/encode/httpx/HEAD/httpx/_utils.py
Write proper docstrings for these functions
from __future__ import annotations import codecs import datetime import email.message import json as jsonlib import re import typing import urllib.request from collections.abc import Mapping from http.cookiejar import Cookie, CookieJar from ._content import ByteStream, UnattachedStream, encode_request, encode_respons...
--- +++ @@ -54,6 +54,9 @@ def _is_known_encoding(encoding: str) -> bool: + """ + Return `True` if `encoding` is a known codec. + """ try: codecs.lookup(encoding) except LookupError: @@ -62,10 +65,16 @@ def _normalize_header_key(key: str | bytes, encoding: str | None = None) -> bytes:...
https://raw.githubusercontent.com/encode/httpx/HEAD/httpx/_models.py
Add detailed documentation for each class
from __future__ import annotations import codecs import io import typing import zlib from ._exceptions import DecodingError # Brotli support is optional try: # The C bindings in `brotli` are recommended for CPython. import brotli except ImportError: # pragma: no cover try: # The CFFI bindings i...
--- +++ @@ -1,3 +1,8 @@+""" +Handlers for Content-Encoding. + +See: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Encoding +""" from __future__ import annotations @@ -37,6 +42,9 @@ class IdentityDecoder(ContentDecoder): + """ + Handle unencoded data. + """ def decode(self, d...
https://raw.githubusercontent.com/encode/httpx/HEAD/httpx/_decoders.py
Create documentation strings for testing functions
from __future__ import annotations import inspect import warnings from json import dumps as json_dumps from typing import ( Any, AsyncIterable, AsyncIterator, Iterable, Iterator, Mapping, ) from urllib.parse import urlencode from ._exceptions import StreamClosed, StreamConsumed from ._multipar...
--- +++ @@ -90,6 +90,11 @@ class UnattachedStream(AsyncByteStream, SyncByteStream): + """ + If a request or response is serialized using pickle, then it is no longer + attached to a stream for I/O purposes. Any stream operations should result + in `httpx.StreamClosed`. + """ def __iter__(self)...
https://raw.githubusercontent.com/encode/httpx/HEAD/httpx/_content.py
Add docstrings for internal functions
from __future__ import annotations import hashlib import os import re import time import typing from base64 import b64encode from urllib.request import parse_http_list from ._exceptions import ProtocolError from ._models import Cookies, Request, Response from ._utils import to_bytes, to_str, unquote if typing.TYPE_C...
--- +++ @@ -20,16 +20,54 @@ class Auth: + """ + Base class for all authentication schemes. + + To implement a custom authentication scheme, subclass `Auth` and override + the `.auth_flow()` method. + + If the authentication scheme does I/O such as disk access or network calls, or uses + synchroniz...
https://raw.githubusercontent.com/encode/httpx/HEAD/httpx/_auth.py
Annotate my code with docstrings
from __future__ import annotations from enum import IntEnum __all__ = ["codes"] class codes(IntEnum): def __new__(cls, value: int, phrase: str = "") -> codes: obj = int.__new__(cls, value) obj._value_ = value obj.phrase = phrase # type: ignore[attr-defined] return obj def...
--- +++ @@ -6,6 +6,24 @@ class codes(IntEnum): + """HTTP status codes and reason phrases + + Status codes from the following RFCs are all observed: + + * RFC 7231: Hypertext Transfer Protocol (HTTP/1.1), obsoletes 2616 + * RFC 6585: Additional HTTP Status Codes + * RFC 3229: Delta encodin...
https://raw.githubusercontent.com/encode/httpx/HEAD/httpx/_status_codes.py
Insert docstrings into my code
from __future__ import annotations import contextlib import typing if typing.TYPE_CHECKING: from ._models import Request, Response # pragma: no cover __all__ = [ "CloseError", "ConnectError", "ConnectTimeout", "CookieConflict", "DecodingError", "HTTPError", "HTTPStatusError", "I...
--- +++ @@ -1,3 +1,35 @@+""" +Our exception hierarchy: + +* HTTPError + x RequestError + + TransportError + - TimeoutException + · ConnectTimeout + · ReadTimeout + · WriteTimeout + · PoolTimeout + - NetworkError + · ConnectError + · ReadError + · WriteError...
https://raw.githubusercontent.com/encode/httpx/HEAD/httpx/_exceptions.py
Add docstrings including usage examples
from __future__ import annotations import io import mimetypes import os import re import typing from pathlib import Path from ._types import ( AsyncByteStream, FileContent, FileTypes, RequestData, RequestFiles, SyncByteStream, ) from ._utils import ( peek_filelike_length, primitive_val...
--- +++ @@ -31,6 +31,9 @@ def _format_form_param(name: str, value: str) -> bytes: + """ + Encode a name/value pair within a multipart form. + """ def replacer(match: typing.Match[str]) -> str: return _HTML5_FORM_ENCODING_REPLACEMENTS[match.group(0)] @@ -40,6 +43,11 @@ def _guess_content...
https://raw.githubusercontent.com/encode/httpx/HEAD/httpx/_multipart.py
Auto-generate documentation strings for this file
from __future__ import annotations import typing from urllib.parse import parse_qs, unquote, urlencode import idna from ._types import QueryParamTypes from ._urlparse import urlparse from ._utils import primitive_value_to_str __all__ = ["URL", "QueryParams"] class URL: def __init__(self, url: URL | str = "",...
--- +++ @@ -13,6 +13,66 @@ class URL: + """ + url = httpx.URL("HTTPS://jo%40email.com:a%20secret@müller.de:1234/pa%20th?search=ab#anchorlink") + + assert url.scheme == "https" + assert url.username == "jo@email.com" + assert url.password == "a secret" + assert url.userinfo == b"jo%40email.com:a%20...
https://raw.githubusercontent.com/encode/httpx/HEAD/httpx/_urls.py
Add professional docstrings to my codebase
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # vim:ts=4:sw=4:softtabstop=4:smarttab:expandtab # to work around tk_chooseDirectory not properly returning unicode paths on Windows # need to use a dialog that can be hacked up to actually return full unicode paths # originally based on AskFolder from EasyDialogs for Win...
--- +++ @@ -31,6 +31,9 @@ # Adjusted for Python 3, September 2020 +""" +AskFolder(...) -- Ask the user to select a folder Windows specific +""" import os @@ -155,6 +158,10 @@ actionButtonLabel=None, cancelButtonLabel=None, multiple=None): + """Display a dialog asking the user for s...
https://raw.githubusercontent.com/apprenticeharper/DeDRM_tools/HEAD/DeDRM_plugin/askfolder_ed.py
Document classes and their methods
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # ineptpdf.py # Copyright © 2009-2020 by i♥cabbages, Apprentice Harper et al. # Released under the terms of the GNU General Public Licence, version 3 # <http://www.gnu.org/licenses/> # Revision history: # 1 - Initial release # 2 - Improved determination of key-gene...
--- +++ @@ -47,6 +47,9 @@ # 8.0.6 - Replace use of float by Decimal for greater precision, and import tkFileDialog # 9.0.0 - Add Python 3 compatibility for calibre 5 +""" +Decrypts Adobe ADEPT-encrypted PDF files. +""" __license__ = 'GPL v3' __version__ = "9.0.0" @@ -420,6 +423,7 @@ # Utilities def chopl...
https://raw.githubusercontent.com/apprenticeharper/DeDRM_tools/HEAD/DeDRM_plugin/ineptpdf.py
Fill in missing docstrings in my code
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # androidkindlekey.py # Copyright © 2010-20 by Thom, Apprentice Harper et al. # Revision history: # 1.0 - AmazonSecureStorage.xml decryption to serial number # 1.1 - map_data_storage.db decryption to serial number # 1.2 - Changed to be callable from AppleScript ...
--- +++ @@ -15,6 +15,9 @@ # 1.5 - Fix another problem identified by Aldo Bleeker # 2.0 - Python 3 compatibility +""" +Retrieve Kindle for Android Serial Number. +""" __license__ = 'GPL v3' __version__ = '2.0' @@ -100,6 +103,9 @@ STORAGE2 = "map_data_storage.db" class AndroidObfuscation(object): + '''...
https://raw.githubusercontent.com/apprenticeharper/DeDRM_tools/HEAD/DeDRM_plugin/androidkindlekey.py
Document functions with clear intent
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # ignoblepdf.py # Copyright © 2009-2020 by Apprentice Harper et al. # Released under the terms of the GNU General Public Licence, version 3 # <http://www.gnu.org/licenses/> # Based on version 8.0.6 of ineptpdf.py # Revision history: # 0.1 - Initial alpha testing r...
--- +++ @@ -16,6 +16,9 @@ # 0.2 - Python 3 for calibre 5.0 (in testing) +""" +Decrypts Barnes & Noble encrypted PDF files. +""" __license__ = 'GPL v3' __version__ = "0.2" @@ -251,6 +254,7 @@ # Utilities def choplist(n, seq): + '''Groups every n elements of the list.''' r = [] for x in seq: ...
https://raw.githubusercontent.com/apprenticeharper/DeDRM_tools/HEAD/DeDRM_plugin/ignoblepdf.py
Turn comments into proper docstrings
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # kindlekey.py # Copyright © 2008-2020 Apprentice Harper et al. __license__ = 'GPL v3' __version__ = '3.0' # Revision history: # 1.0 - Kindle info file decryption, extracted from k4mobidedrm, etc. # 1.1 - Added Tkinter to match adobekey.py # 1.2 - Fixed testing...
--- +++ @@ -134,6 +134,11 @@ # For K4M/PC 1.6.X and later def primes(n): + """ + Return a list of prime integers smaller than or equal to n + :param n: int + :return: list->int + """ if n == 2: return [2] elif n < 2: @@ -211,18 +216,25 @@ """ class CryptoError(Exc...
https://raw.githubusercontent.com/apprenticeharper/DeDRM_tools/HEAD/DeDRM_plugin/kindlekey.py
Create documentation strings for testing functions
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # vim:fileencoding=UTF-8:ts=4:sw=4:sta:et:sts=4:ai __license__ = 'GPL v3' __copyright__ = '2012, David Forrester <davidfor@internode.on.net>' __docformat__ = 'restructuredtext en' import os, time, re, sys from datetime import datetime from PyQt5.Qt import (Qt, QIcon, Q...
--- +++ @@ -44,11 +44,20 @@ pass # load_translations() added in calibre 1.9 def set_plugin_icon_resources(name, resources): + ''' + Set our global store of plugin name and icon resources for sharing between + the InterfaceAction class which reads them and the ConfigWidget + if needed for use on the c...
https://raw.githubusercontent.com/apprenticeharper/DeDRM_tools/HEAD/Obok_plugin/common_utils.py
Document all public functions with docstrings
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # Version 4.1.0 February 2021 # Add detection for Kobo directory location on Linux # Version 4.0.0 September 2020 # Python 3.0 # # Version 3.2.5 December 2016 # Improve detection of good text decryption. # # Version 3.2.4 December 2016 # Remove incorrect support for Kobo...
--- +++ @@ -155,6 +155,7 @@ # too, if you like - you can do that with a real book # after all. # +"""Manage all Kobo books, either encrypted or DRM-free.""" from __future__ import print_function __version__ = '4.0.0' @@ -290,6 +291,11 @@ class KoboLibrary(object): + """The Kobo library. + + This class r...
https://raw.githubusercontent.com/apprenticeharper/DeDRM_tools/HEAD/Obok_plugin/obok/obok.py
Annotate my code with docstrings
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # vim:fileencoding=UTF-8:ts=4:sw=4:sta:et:sts=4:ai __license__ = 'GPL v3' __docformat__ = 'restructuredtext en' import os, struct, time try: from StringIO import StringIO except ImportError: from io import StringIO from traceback import print_exc from PyQt5.Q...
--- +++ @@ -60,17 +60,31 @@ pass # load_translations() added in calibre 1.9 def format_plural(number, possessive=False): + ''' + Cosmetic ditty to provide the proper string formatting variable to handle singular/plural situations + + :param: number: variable that represents the count/len of something + ...
https://raw.githubusercontent.com/apprenticeharper/DeDRM_tools/HEAD/Obok_plugin/utilities.py
Generate consistent documentation across files
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import struct, os, time, sys, shutil import binascii, stat import io import re from io import BytesIO try: import zlib # We may need its compression method crc32 = zlib.crc32 except ImportError: zlib = None crc32 = binascii.crc32 __all__ = ["BadZipfile"...
--- +++ @@ -1,6 +1,9 @@ #!/usr/bin/env python3 # -*- coding: utf-8 -*- +""" +Read and write ZIP files. +""" import struct, os, time, sys, shutil import binascii, stat import io @@ -23,6 +26,10 @@ class LargeZipFile(Exception): + """ + Raised when writing a zipfile, the zipfile requires ZIP64 extensions ...
https://raw.githubusercontent.com/apprenticeharper/DeDRM_tools/HEAD/DeDRM_plugin/zipfilerugged.py
Add docstrings with type hints explained
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # vim:fileencoding=UTF-8:ts=4:sw=4:sta:et:sts=4:ai _license__ = 'GPL v3' __docformat__ = 'restructuredtext en' import codecs import os, traceback, zipfile try: from PyQt5.Qt import QToolButton, QUrl except ImportError: from PyQt4.Qt import QToolButton, QUrl ...
--- +++ @@ -60,6 +60,9 @@ self.gui.keyboard.finalize() def launchObok(self): + ''' + Main processing/distribution method + ''' self.count = 0 self.books_to_add = [] self.formats_to_add = [] @@ -187,6 +190,9 @@ return def show_help(self): + ...
https://raw.githubusercontent.com/apprenticeharper/DeDRM_tools/HEAD/Obok_plugin/action.py
Include argument descriptions in docstrings
# vim:fileencoding=UTF-8:ts=4:sw=4:sta:et:sts=4:ai from __future__ import (unicode_literals, division, absolute_import, print_function) __license__ = 'GPL v3' __docformat__ = 'restructuredtext en' TEXT_DRM_FREE = ' (*: drm - free)' LAB_DRM_FREE = '* : drm - free' try: from PyQt5.Qt impo...
--- +++ @@ -41,7 +41,15 @@ pass # load_translations() added in calibre 1.9 class SelectionDialog(SizePersistedDialog): + ''' + Dialog to select the kobo books to decrypt + ''' def __init__(self, gui, interface_action, books): + ''' + :param gui: Parent gui + :param interface_ac...
https://raw.githubusercontent.com/apprenticeharper/DeDRM_tools/HEAD/Obok_plugin/dialogs.py
Add missing documentation to my Python functions
# vim:fileencoding=UTF-8:ts=4:sw=4:sta:et:sts=4:ai from __future__ import (unicode_literals, division, absolute_import, print_function) __license__ = 'GPL v3' __version__ = '7.2.1' __docformat__ = 'restructuredtext en' ##################################################################### # P...
--- +++ @@ -41,12 +41,36 @@ actual_plugin = 'calibre_plugins.'+PLUGIN_SAFE_NAME+'.action:InterfacePluginAction' def is_customizable(self): + ''' + This method must return True to enable customization via + Preferences->Plugins + ''' return True def config...
https://raw.githubusercontent.com/apprenticeharper/DeDRM_tools/HEAD/Obok_plugin/__init__.py
Write docstrings for algorithm functions
#!/usr/bin/env python # -*- coding: utf-8 -*- # Version 3.2.5 December 2016 # Improve detection of good text decryption. # # Version 3.2.4 December 2016 # Remove incorrect support for Kobo Desktop under Wine # # Version 3.2.3 October 2016 # Fix for windows network user and more xml fixes # # Version 3.2.2 October 2016...
--- +++ @@ -149,6 +149,7 @@ # too, if you like - you can do that with a real book # after all. # +"""Manage all Kobo books, either encrypted or DRM-free.""" from __future__ import print_function __version__ = '3.2.4' @@ -284,6 +285,11 @@ class KoboLibrary(object): + """The Kobo library. + + This class r...
https://raw.githubusercontent.com/apprenticeharper/DeDRM_tools/HEAD/Other_Tools/Kobo/obok.py
Add missing documentation to my Python functions
#!/usr/bin/env python3 # -*- coding: utf-8 -*- class CryptoError(Exception): def __init__(self,errorMessage='Error!'): self.message = errorMessage def __str__(self): return self.message class InitCryptoError(CryptoError): class BadKeySizeError(InitCryptoError): class EncryptError(CryptoError)...
--- +++ @@ -1,20 +1,43 @@ #!/usr/bin/env python3 # -*- coding: utf-8 -*- +""" + Routines for doing AES CBC in one file + + Modified by some_updates to extract + and combine only those parts needed for AES CBC + into one simple to add python file + + Original Version + Copyright (c) 2002 by Paul A. ...
https://raw.githubusercontent.com/apprenticeharper/DeDRM_tools/HEAD/DeDRM_plugin/aescbc.py
Include argument descriptions in docstrings
from __future__ import annotations import logging import os.path import sys from collections.abc import Mapping from pre_commit.errors import FatalError from pre_commit.util import CalledProcessError from pre_commit.util import cmd_output from pre_commit.util import cmd_output_b logger = logging.getLogger(__name__) ...
--- +++ @@ -208,6 +208,7 @@ def check_for_cygwin_mismatch() -> None: + """See https://github.com/pre-commit/pre-commit/issues/354""" if sys.platform in ('cygwin', 'win32'): # pragma: no cover (windows) is_cygwin_python = sys.platform == 'cygwin' try: @@ -230,10 +231,15 @@ def get_best...
https://raw.githubusercontent.com/pre-commit/pre-commit/HEAD/pre_commit/git.py
Add docstrings to make code maintainable
from __future__ import annotations import concurrent.futures import os.path import re import tempfile from collections.abc import Sequence from typing import Any from typing import NamedTuple import pre_commit.constants as C from pre_commit import git from pre_commit import output from pre_commit import xargs from pr...
--- +++ @@ -121,6 +121,7 @@ rev_infos: list[RevInfo | None], retry: bool = False, ) -> tuple[list[str], list[int]]: + """detect `rev:` lines or reformat the file""" with open(path, newline='') as f: original = f.read() @@ -165,6 +166,7 @@ repos: Sequence[str] = (), ...
https://raw.githubusercontent.com/pre-commit/pre-commit/HEAD/pre_commit/commands/autoupdate.py
Document my Python code with docstrings
from __future__ import annotations import contextlib import errno import importlib.resources import os.path import shutil import stat import subprocess import sys from collections.abc import Callable from collections.abc import Generator from types import TracebackType from typing import Any from pre_commit import pa...
--- +++ @@ -26,6 +26,7 @@ @contextlib.contextmanager def clean_path_on_failure(path: str) -> Generator[None]: + """Cleans up the directory on an exceptional failure.""" try: yield except BaseException: @@ -230,8 +231,9 @@ shutil.rmtree(path, ignore_errors=False, onerror=_handle_readonly...
https://raw.githubusercontent.com/pre-commit/pre-commit/HEAD/pre_commit/util.py
Generate NumPy-style docstrings
from __future__ import annotations import contextlib import os import shlex import shutil import tempfile import textwrap from collections.abc import Generator from collections.abc import Sequence from pre_commit import lang_base from pre_commit.envcontext import envcontext from pre_commit.envcontext import PatchesT ...
--- +++ @@ -109,6 +109,10 @@ @contextlib.contextmanager def _r_code_in_tempfile(code: str) -> Generator[str]: + """ + To avoid quoting and escaping issues, avoid `Rscript [options] -e {expr}` + but use `Rscript [options] path/to/file_with_expr.R` + """ with tempfile.TemporaryDirectory() as tmpdir: ...
https://raw.githubusercontent.com/pre-commit/pre-commit/HEAD/pre_commit/languages/r.py
Provide clean and structured docstrings
from __future__ import annotations import argparse import os import sys if sys.platform == 'win32': # pragma: no cover (windows) def _enable() -> None: from ctypes import POINTER from ctypes import windll from ctypes import WinError from ctypes import WINFUNCTYPE from ctyp...
--- +++ @@ -65,6 +65,13 @@ def format_color(text: str, color: str, use_color_setting: bool) -> str: + """Format text with color. + + Args: + text - Text to be formatted with color if `use_color` + color - The color start string + use_color_setting - Whether or not to color + """ i...
https://raw.githubusercontent.com/pre-commit/pre-commit/HEAD/pre_commit/color.py
Add return value explanations in docstrings
from __future__ import annotations import contextlib import logging import os.path import sqlite3 import tempfile from collections.abc import Callable from collections.abc import Generator from collections.abc import Sequence import pre_commit.constants as C from pre_commit import clientlib from pre_commit import fil...
--- +++ @@ -23,6 +23,12 @@ def _get_default_directory() -> str: + """Returns the default directory for the Store. This is intentionally + underscored to indicate that `Store.get_default_directory` is the intended + way to get this information. This is also done so + `Store.get_default_directory` can b...
https://raw.githubusercontent.com/pre-commit/pre-commit/HEAD/pre_commit/store.py
Add docstrings to incomplete code
import logging import os from typing import List, Optional from urllib.parse import unquote import google.generativeai as genai from adalflow.components.model_client.ollama_client import OllamaClient from adalflow.core.types import ModelType from fastapi import FastAPI, HTTPException from fastapi.middleware.cors impor...
--- +++ @@ -54,6 +54,9 @@ content: str class ChatCompletionRequest(BaseModel): + """ + Model for requesting a chat completion. + """ repo_url: str = Field(..., description="URL of the repository to query") messages: List[ChatMessage] = Field(..., description="List of chat messages") fileP...
https://raw.githubusercontent.com/AsyncFuncAI/deepwiki-open/HEAD/api/simple_chat.py
Write docstrings for algorithm functions
from typing import Sequence, List from copy import deepcopy from tqdm import tqdm import logging import adalflow as adal from adalflow.core.types import Document from adalflow.core.component import DataComponent import requests import os # Configure logging from api.logging_config import setup_logging setup_logging()...
--- +++ @@ -15,9 +15,20 @@ logger = logging.getLogger(__name__) class OllamaModelNotFoundError(Exception): + """Custom exception for when Ollama model is not found""" pass def check_ollama_model_exists(model_name: str, ollama_host: str = None) -> bool: + """ + Check if an Ollama model exists before ...
https://raw.githubusercontent.com/AsyncFuncAI/deepwiki-open/HEAD/api/ollama_patch.py
Write docstrings for utility functions
from typing import Dict, Sequence, Optional, Any, List import logging import json import aiohttp import requests from requests.exceptions import RequestException, Timeout from adalflow.core.model_client import ModelClient from adalflow.core.types import ( CompletionUsage, ModelType, GeneratorOutput, ) lo...
--- +++ @@ -1,3 +1,4 @@+"""OpenRouter ModelClient integration.""" from typing import Dict, Sequence, Optional, Any, List import logging @@ -36,11 +37,13 @@ """ def __init__(self, *args, **kwargs) -> None: + """Initialize the OpenRouter client.""" super().__init__(*args, **kwargs) ...
https://raw.githubusercontent.com/AsyncFuncAI/deepwiki-open/HEAD/api/openrouter_client.py
Add well-formatted docstrings
import os import logging from fastapi import FastAPI, HTTPException, Query, Request, WebSocket from fastapi.middleware.cors import CORSMiddleware from fastapi.responses import JSONResponse, Response from typing import List, Optional, Dict, Any, Literal import json from datetime import datetime from pydantic import Base...
--- +++ @@ -38,6 +38,9 @@ # --- Pydantic Models --- class WikiPage(BaseModel): + """ + Model for a wiki page. + """ id: str title: str content: str @@ -64,6 +67,9 @@ class WikiSection(BaseModel): + """ + Model for the wiki sections. + """ id: str title: str pages: ...
https://raw.githubusercontent.com/AsyncFuncAI/deepwiki-open/HEAD/api/api.py
Generate docstrings for script automation
import logging import os from typing import List, Optional, Dict, Any from urllib.parse import unquote import google.generativeai as genai from adalflow.components.model_client.ollama_client import OllamaClient from adalflow.core.types import ModelType from fastapi import WebSocket, WebSocketDisconnect, HTTPException ...
--- +++ @@ -38,6 +38,9 @@ content: str class ChatCompletionRequest(BaseModel): + """ + Model for requesting a chat completion. + """ repo_url: str = Field(..., description="URL of the repository to query") messages: List[ChatMessage] = Field(..., description="List of chat messages") fileP...
https://raw.githubusercontent.com/AsyncFuncAI/deepwiki-open/HEAD/api/websocket_wiki.py
Add docstrings including usage examples
import os import pickle from typing import ( Dict, Optional, Any, Callable, Generator, Union, Literal, List, Sequence, ) import logging import backoff from copy import deepcopy from tqdm import tqdm # optional import from adalflow.utils.lazy_import import safe_import, OptionalPack...
--- +++ @@ -1,3 +1,4 @@+"""Dashscope (Alibaba Cloud) ModelClient integration.""" import os import pickle @@ -65,6 +66,7 @@ log = logging.getLogger(__name__) def get_first_message_content(completion: ChatCompletion) -> str: + """When we only need the content of the first message.""" log.info(f"🔍 get_firs...
https://raw.githubusercontent.com/AsyncFuncAI/deepwiki-open/HEAD/api/dashscope_client.py
Add concise docstrings to each method
import os import base64 from typing import ( Dict, Sequence, Optional, List, Any, TypeVar, Callable, Generator, Union, Literal, ) import re import logging import backoff # optional import from adalflow.utils.lazy_import import safe_import, OptionalPackages from openai.types.ch...
--- +++ @@ -1,3 +1,4 @@+"""OpenAI ModelClient integration.""" import os import base64 @@ -55,6 +56,8 @@ # completion parsing functions and you can combine them into one singple chat completion parser def get_first_message_content(completion: ChatCompletion) -> str: + r"""When we only need the content of the f...
https://raw.githubusercontent.com/AsyncFuncAI/deepwiki-open/HEAD/api/openai_client.py
Write beginner-friendly docstrings
import os import logging import backoff from typing import Dict, Any, Optional, List, Sequence from adalflow.core.model_client import ModelClient from adalflow.core.types import ModelType, EmbedderOutput try: import google.generativeai as genai from google.generativeai.types.text_types import EmbeddingDict, ...
--- +++ @@ -1,3 +1,4 @@+"""Google AI Embeddings ModelClient integration.""" import os import logging @@ -54,12 +55,19 @@ api_key: Optional[str] = None, env_api_key_name: str = "GOOGLE_API_KEY", ): + """Initialize Google AI Embeddings client. + + Args: + api_key...
https://raw.githubusercontent.com/AsyncFuncAI/deepwiki-open/HEAD/api/google_embedder_client.py
Add verbose docstrings with examples
import os from typing import ( Dict, Sequence, Optional, List, Any, TypeVar, Callable, Generator, Union, Literal, ) import re import logging import backoff # optional import from adalflow.utils.lazy_import import safe_import, OptionalPackages import sys openai = safe_import(...
--- +++ @@ -1,3 +1,4 @@+"""AzureOpenAI ModelClient integration.""" import os from typing import ( @@ -72,6 +73,8 @@ # completion parsing functions and you can combine them into one singple chat completion parser def get_first_message_content(completion: ChatCompletion) -> str: + r"""When we only need the cont...
https://raw.githubusercontent.com/AsyncFuncAI/deepwiki-open/HEAD/api/azureai_client.py
Fully document this Python code with docstrings
import os import json import logging import boto3 import botocore import backoff from typing import Dict, Any, Optional, List, Generator, Union, AsyncGenerator, Sequence from adalflow.core.model_client import ModelClient from adalflow.core.types import ModelType, GeneratorOutput, EmbedderOutput # Configure logging f...
--- +++ @@ -1,3 +1,4 @@+"""AWS Bedrock ModelClient integration.""" import os import json @@ -44,6 +45,15 @@ *args, **kwargs ) -> None: + """Initialize the AWS Bedrock client. + + Args: + aws_access_key_id: AWS access key ID. If not provided, will use environmen...
https://raw.githubusercontent.com/AsyncFuncAI/deepwiki-open/HEAD/api/bedrock_client.py
Include argument descriptions in docstrings
import adalflow as adal from adalflow.core.types import Document, List from adalflow.components.data_process import TextSplitter, ToEmbeddings import os import subprocess import json import tiktoken import logging import base64 import glob from adalflow.utils import get_adalflow_default_root_path from adalflow.core.db ...
--- +++ @@ -25,6 +25,19 @@ MAX_EMBEDDING_TOKENS = 8192 def count_tokens(text: str, embedder_type: str = None, is_ollama_embedder: bool = None) -> int: + """ + Count the number of tokens in a text string using tiktoken. + + Args: + text (str): The text to count tokens for. + embedder_type (str,...
https://raw.githubusercontent.com/AsyncFuncAI/deepwiki-open/HEAD/api/data_pipeline.py
Turn comments into proper docstrings
import logging import weakref import re from dataclasses import dataclass from typing import Any, List, Tuple, Dict from uuid import uuid4 import adalflow as adal from api.tools.embedder import get_embedder from api.prompts import RAG_SYSTEM_PROMPT as system_prompt, RAG_TEMPLATE # Create our own implementation of th...
--- +++ @@ -26,11 +26,13 @@ assistant_response: AssistantResponse class CustomConversation: + """Custom implementation of Conversation to fix the list assignment index out of range error""" def __init__(self): self.dialog_turns = [] def append_dialog_turn(self, dialog_turn): + ""...
https://raw.githubusercontent.com/AsyncFuncAI/deepwiki-open/HEAD/api/rag.py
Add docstrings that explain logic
import os import json import logging import re from pathlib import Path from typing import List, Union, Dict, Any logger = logging.getLogger(__name__) from api.openai_client import OpenAIClient from api.openrouter_client import OpenRouterClient from api.bedrock_client import BedrockClient from api.google_embedder_cli...
--- +++ @@ -67,6 +67,11 @@ } def replace_env_placeholders(config: Union[Dict[str, Any], List[Any], str, Any]) -> Union[Dict[str, Any], List[Any], str, Any]: + """ + Recursively replace placeholders like "${ENV_VAR}" in string values + within a nested configuration structure (dicts, lists, strings) + with...
https://raw.githubusercontent.com/AsyncFuncAI/deepwiki-open/HEAD/api/config.py
Write docstrings describing functionality
import asyncio import functools import linecache import sys from dataclasses import dataclass from dataclasses import field from typing import IO from typing import Any from typing import Callable from typing import Dict from typing import Iterable from typing import Iterator from typing import Optional from typing imp...
--- +++ @@ -55,6 +55,7 @@ @dataclass class Frame: + """A frame in the tree""" location: Optional[StackElement] value: int @@ -67,6 +68,7 @@ @dataclass class ElidedLocations: + """Information about allocations locations below the configured threshold.""" cutoff: int = 0 n_locations: i...
https://raw.githubusercontent.com/bloomberg/memray/HEAD/src/memray/reporters/tree.py
Add detailed docstrings explaining each function
# The JS variant implements "OrderedCollection", which basically completely # overlaps with ``list``. So we'll cheat. :D class OrderedCollection(list): pass class Strength(object): REQUIRED = None STRONG_PREFERRED = None PREFERRED = None STRONG_DEFAULT = None NORMAL = None WEAK_DEFAULT = ...
--- +++ @@ -1,3 +1,22 @@+""" +deltablue.py +============ + +Ported for the PyPy project. +Contributed by Daniel Lindsley + +This implementation of the DeltaBlue benchmark was directly ported +from the `V8's source code`_, which was in turn derived +from the Smalltalk implementation by John Maloney and Mario +Wolczko. T...
https://raw.githubusercontent.com/bloomberg/memray/HEAD/benchmarks/benchmarking/cases/deltablue_base.py
Add professional docstrings to my codebase
import pyperf from memray_helper import get_tracker __author__ = "collinwinter@google.com (Collin Winter)" # Pure-Python implementation of itertools.permutations(). def permutations(iterable, r=None): pool = tuple(iterable) n = len(pool) if r is None: r = n indices = list(range(n)) cycle...
--- +++ @@ -1,3 +1,4 @@+"""Simple, brute-force N-Queens solver.""" import pyperf from memray_helper import get_tracker @@ -7,6 +8,7 @@ # Pure-Python implementation of itertools.permutations(). def permutations(iterable, r=None): + """permutations(range(3), 2) --> (0,1) (0,2) (1,0) (1,2) (2,0) (2,1)""" po...
https://raw.githubusercontent.com/bloomberg/memray/HEAD/benchmarks/benchmarking/cases/nqueens_memray.py
Create Google-style docstrings for my code
import math import random SIZE = 9 GAMES = 200 KOMI = 7.5 EMPTY, WHITE, BLACK = 0, 1, 2 SHOW = {EMPTY: ".", WHITE: "o", BLACK: "x"} PASS = -1 MAXMOVES = SIZE * SIZE * 3 TIMESTAMP = 0 MOVES = 0 def to_pos(x, y): return y * SIZE + x def to_xy(pos): y, x = divmod(pos, SIZE) return x, y class Square: ...
--- +++ @@ -1,3 +1,6 @@+""" +Go board game +""" import math import random @@ -328,6 +331,7 @@ self.parent = None def play(self, board): + """uct tree search""" color = board.color node = self path = [node] @@ -350,6 +354,7 @@ self.update_path(board, color, pa...
https://raw.githubusercontent.com/bloomberg/memray/HEAD/benchmarks/benchmarking/cases/go_base.py
Add docstrings that explain purpose and usage
__author__ = "collinwinter@google.com (Collin Winter)" # Pure-Python implementation of itertools.permutations(). def permutations(iterable, r=None): pool = tuple(iterable) n = len(pool) if r is None: r = n indices = list(range(n)) cycles = list(range(n - r + 1, n + 1))[::-1] yield tup...
--- +++ @@ -1,9 +1,11 @@+"""Simple, brute-force N-Queens solver.""" __author__ = "collinwinter@google.com (Collin Winter)" # Pure-Python implementation of itertools.permutations(). def permutations(iterable, r=None): + """permutations(range(3), 2) --> (0,1) (0,2) (1,0) (1,2) (2,0) (2,1)""" pool = tuple...
https://raw.githubusercontent.com/bloomberg/memray/HEAD/benchmarks/benchmarking/cases/nqueens_base.py
Generate missing documentation strings
__contact__ = "collinwinter@google.com (Collin Winter)" DEFAULT_ITERATIONS = 20000 DEFAULT_REFERENCE = "sun" def combinations(l): result = [] for x in range(len(l) - 1): ls = l[x + 1 :] for y in ls: result.append((l[x], y)) return result PI = 3.14159265358979323 SOLAR_MASS =...
--- +++ @@ -1,3 +1,18 @@+""" +N-body benchmark from the Computer Language Benchmarks Game. + +This is intended to support Unladen Swallow's pyperf.py. Accordingly, it has been +modified from the Shootout version: +- Accept standard Unladen Swallow benchmark options. +- Run report_energy()/advance() in a loop. +- Reimpl...
https://raw.githubusercontent.com/bloomberg/memray/HEAD/benchmarks/benchmarking/cases/nbody_base.py
Help me comply with documentation standards
import math import random import pyperf from memray_helper import get_tracker SIZE = 9 GAMES = 200 KOMI = 7.5 EMPTY, WHITE, BLACK = 0, 1, 2 SHOW = {EMPTY: ".", WHITE: "o", BLACK: "x"} PASS = -1 MAXMOVES = SIZE * SIZE * 3 TIMESTAMP = 0 MOVES = 0 def to_pos(x, y): return y * SIZE + x def to_xy(pos): y, x =...
--- +++ @@ -1,3 +1,6 @@+""" +Go board game +""" import math import random @@ -332,6 +335,7 @@ self.parent = None def play(self, board): + """uct tree search""" color = board.color node = self path = [node] @@ -354,6 +358,7 @@ self.update_path(board, color, pa...
https://raw.githubusercontent.com/bloomberg/memray/HEAD/benchmarks/benchmarking/cases/go_memray.py
Generate descriptive docstrings automatically
from typing import Any class MemrayError(Exception): class MemrayCommandError(MemrayError): def __init__(self, *args: Any, exit_code: int) -> None: super().__init__(*args) self.exit_code = exit_code
--- +++ @@ -2,10 +2,12 @@ class MemrayError(Exception): + """Exceptions raised in this package.""" class MemrayCommandError(MemrayError): + """Exceptions raised from this package's CLI commands.""" def __init__(self, *args: Any, exit_code: int) -> None: super().__init__(*args) - se...
https://raw.githubusercontent.com/bloomberg/memray/HEAD/src/memray/_errors.py
Add docstrings with type hints explained
import pyperf from memray_helper import get_tracker __contact__ = "collinwinter@google.com (Collin Winter)" DEFAULT_ITERATIONS = 20000 DEFAULT_REFERENCE = "sun" def combinations(l): result = [] for x in range(len(l) - 1): ls = l[x + 1 :] for y in ls: result.append((l[x], y)) ...
--- +++ @@ -1,3 +1,18 @@+""" +N-body benchmark from the Computer Language Benchmarks Game. + +This is intended to support Unladen Swallow's pyperf.py. Accordingly, it has been +modified from the Shootout version: +- Accept standard Unladen Swallow benchmark options. +- Run report_energy()/advance() in a loop. +- Reimpl...
https://raw.githubusercontent.com/bloomberg/memray/HEAD/benchmarks/benchmarking/cases/nbody_memray.py
Fully document this Python code with docstrings
import contextlib import os import pathlib import sys import threading from collections import defaultdict from collections import deque from dataclasses import dataclass from datetime import datetime from functools import total_ordering from math import ceil from typing import Any from typing import DefaultDict from t...
--- +++ @@ -199,6 +199,9 @@ memory_threshold: float = float("inf"), native_traces: Optional[bool] = False, ) -> Dict[Location, AllocationEntry]: + """Take allocation records and for each frame contained, record "own" + allocations which happened on the frame, and sum up allocations on + all of the ch...
https://raw.githubusercontent.com/bloomberg/memray/HEAD/src/memray/reporters/tui.py
Document all endpoints with docstrings
from bisect import bisect import pyperf from memray_helper import get_tracker SOLVE_ARG = 60 WIDTH, HEIGHT = 5, 10 DIR_NO = 6 S, E = WIDTH * HEIGHT, 2 SE = S + (E / 2) SW = SE - E W, NW, NE = -E, -SE, -SW SOLUTIONS = [ "00001222012661126155865558633348893448934747977799", "00001222012771127148774485464855...
--- +++ @@ -1,3 +1,12 @@+""" +Meteor Puzzle board: +http://benchmarksgame.alioth.debian.org/u32/meteor-description.html#meteor + +The Computer Language Benchmarks Game +http://benchmarksgame.alioth.debian.org/ + +contributed by Daniel Nanz, 2008-08-21 +""" from bisect import bisect @@ -98,6 +107,7 @@ def conve...
https://raw.githubusercontent.com/bloomberg/memray/HEAD/benchmarks/benchmarking/cases/meteor_context_memray.py
Document classes and their methods
import argparse import ast import contextlib import os import pathlib import runpy import socket import subprocess import sys import textwrap from contextlib import closing from contextlib import suppress from typing import Any from typing import Dict from typing import List from typing import Optional from memray imp...
--- +++ @@ -195,6 +195,7 @@ class RunCommand: + """Run the specified application and track memory usage""" def prepare_parser(self, parser: argparse.ArgumentParser) -> None: parser.usage = "%(prog)s [-m module | -c cmd | file] [args]" @@ -299,6 +300,7 @@ ) def validate_target_file(...
https://raw.githubusercontent.com/bloomberg/memray/HEAD/src/memray/commands/run.py
Add standardized docstrings across the file
import pyperf from memray_helper import get_tracker # The JS variant implements "OrderedCollection", which basically completely # overlaps with ``list``. So we'll cheat. :D class OrderedCollection(list): pass class Strength(object): REQUIRED = None STRONG_PREFERRED = None PREFERRED = None STRONG...
--- +++ @@ -1,3 +1,22 @@+""" +deltablue.py +============ + +Ported for the PyPy project. +Contributed by Daniel Lindsley + +This implementation of the DeltaBlue benchmark was directly ported +from the `V8's source code`_, which was in turn derived +from the Smalltalk implementation by John Maloney and Mario +Wolczko. T...
https://raw.githubusercontent.com/bloomberg/memray/HEAD/benchmarks/benchmarking/cases/deltablue_memray.py
Add docstrings to make code maintainable
from __future__ import annotations import argparse import contextlib import os import pathlib import platform import shlex import shutil import signal import socket import subprocess import sys import tempfile import textwrap import threading import memray from memray._errors import MemrayCommandError from .live imp...
--- +++ @@ -132,6 +132,7 @@ def debugger_inject(debugger: str, pid: int, port: int, verbose: bool) -> str | None: + """Execute a file in a running Python process using a debugger.""" injecter = pathlib.Path(memray.__file__).parent / "_inject.abi3.so" assert injecter.exists() @@ -234,6 +235,7 @@ d...
https://raw.githubusercontent.com/bloomberg/memray/HEAD/src/memray/commands/attach.py
Add documentation for all methods
from bisect import bisect SOLVE_ARG = 60 WIDTH, HEIGHT = 5, 10 DIR_NO = 6 S, E = WIDTH * HEIGHT, 2 SE = S + (E / 2) SW = SE - E W, NW, NE = -E, -SE, -SW SOLUTIONS = [ "00001222012661126155865558633348893448934747977799", "00001222012771127148774485464855968596835966399333", "0000122201277112714877448549...
--- +++ @@ -1,3 +1,12 @@+""" +Meteor Puzzle board: +http://benchmarksgame.alioth.debian.org/u32/meteor-description.html#meteor + +The Computer Language Benchmarks Game +http://benchmarksgame.alioth.debian.org/ + +contributed by Daniel Nanz, 2008-08-21 +""" from bisect import bisect @@ -94,6 +103,7 @@ def conve...
https://raw.githubusercontent.com/bloomberg/memray/HEAD/benchmarks/benchmarking/cases/meteor_context_base.py
Write docstrings including parameters and return values
from functools import lru_cache from typing import Any from typing import Dict from typing import Iterable from typing import Union import jinja2 from markupsafe import Markup from memray import MemorySnapshot from memray import Metadata @lru_cache(maxsize=1) def get_render_environment() -> jinja2.Environment: ...
--- +++ @@ -1,3 +1,4 @@+"""Templates to render reports in HTML.""" from functools import lru_cache from typing import Any from typing import Dict @@ -17,6 +18,8 @@ env = jinja2.Environment(loader=loader) def include_file(name: str) -> Markup: + """Include a file from the templates directory without...
https://raw.githubusercontent.com/bloomberg/memray/HEAD/src/memray/reporters/templates/__init__.py
Document this module using docstrings
import pathlib import typing from dataclasses import dataclass @dataclass(frozen=True) class Destination: pass @dataclass(frozen=True) class FileDestination(Destination): path: typing.Union[pathlib.Path, str] overwrite: bool = False compress_on_exit: bool = True @dataclass(frozen=True) class Sock...
--- +++ @@ -10,6 +10,14 @@ @dataclass(frozen=True) class FileDestination(Destination): + """Specify an output file to write captured allocations into. + + Args: + path: The path to the output file. + overwrite: By default, if a file already exists at that path an + exception will be ra...
https://raw.githubusercontent.com/bloomberg/memray/HEAD/src/memray/_destination.py
Include argument descriptions in docstrings
# Python imports import re # Local imports USE_BYTES = False def re_compile(s): if USE_BYTES: return re.compile(s.encode("latin1")) else: return re.compile(s) # These are the regular expressions to be tested. These sync up, # index-for-index with the list of strings generated by gen_string...
--- +++ @@ -1,3 +1,14 @@+"""Benchmarks for Python's regex engine. + +These are some of the original benchmarks used to tune Python's regex engine +in 2000 written by Fredrik Lundh. Retreived from +http://mail.python.org/pipermail/python-dev/2000-August/007797.html and +integrated into Unladen Swallow's pyperf.py in 200...
https://raw.githubusercontent.com/bloomberg/memray/HEAD/benchmarks/benchmarking/cases/regex_effbot_base.py
Add docstrings to incomplete code
# Python imports import re # Local imports import pyperf from memray_helper import get_tracker USE_BYTES = False def re_compile(s): if USE_BYTES: return re.compile(s.encode("latin1")) else: return re.compile(s) # These are the regular expressions to be tested. These sync up, # index-for-i...
--- +++ @@ -1,3 +1,14 @@+"""Benchmarks for Python's regex engine. + +These are some of the original benchmarks used to tune Python's regex engine +in 2000 written by Fredrik Lundh. Retreived from +http://mail.python.org/pipermail/python-dev/2000-August/007797.html and +integrated into Unladen Swallow's pyperf.py in 200...
https://raw.githubusercontent.com/bloomberg/memray/HEAD/benchmarks/benchmarking/cases/regex_effbot_memray.py
Document classes and their methods
from collections import defaultdict from dataclasses import replace from typing import cast from deepagents.backends.protocol import ( BackendProtocol, EditResult, ExecuteResponse, FileDownloadResponse, FileInfo, FileUploadResponse, GlobResult, GrepMatch, GrepResult, LsResult, ...
--- +++ @@ -1,3 +1,22 @@+"""Composite backend that routes file operations by path prefix. + +Routes operations to different backends based on path prefixes. Use this when you +need different storage strategies for different paths (e.g., state for temp files, +persistent store for memories). + +Examples: + ```python ...
https://raw.githubusercontent.com/langchain-ai/deepagents/HEAD/libs/deepagents/deepagents/backends/composite.py
Add detailed documentation for each class
#!/usr/bin/env python3 import re import sys from pathlib import Path import yaml def validate_skill(skill_path): skill_path = Path(skill_path) # Check SKILL.md exists skill_md = skill_path / "SKILL.md" if not skill_md.exists(): return False, "SKILL.md not found" # Read and validate fro...
--- +++ @@ -1,4 +1,14 @@ #!/usr/bin/env python3 +"""Quick validation script for skills - minimal version. + +For deepagents CLI, skills are located at: +~/.deepagents/<agent>/skills/<skill-name>/ + +Example: +```python +python quick_validate.py ~/.deepagents/agent/skills/my-skill +``` +""" import re import sys @@ -...
https://raw.githubusercontent.com/langchain-ai/deepagents/HEAD/libs/cli/deepagents_cli/built_in_skills/skill-creator/scripts/quick_validate.py
Generate helpful docstrings for debugging
from __future__ import annotations import contextlib import importlib.util import logging import os import tempfile import tomllib from dataclasses import dataclass, field from pathlib import Path from types import MappingProxyType from typing import TYPE_CHECKING, Any, NamedTuple, TypedDict import tomli_w if TYPE_...
--- +++ @@ -1,3 +1,8 @@+"""Model configuration management. + +Handles loading and saving model configuration from TOML files, providing a +structured way to define available models and providers. +""" from __future__ import annotations @@ -21,10 +26,22 @@ class ModelConfigError(Exception): + """Raised when ...
https://raw.githubusercontent.com/langchain-ai/deepagents/HEAD/libs/cli/deepagents_cli/model_config.py
Generate docstrings for script automation
from __future__ import annotations import logging from typing import TYPE_CHECKING, Annotated, Any, Literal, cast if TYPE_CHECKING: from collections.abc import Awaitable, Callable from typing import NotRequired from langchain.agents.middleware.types import ( AgentMiddleware, ContextT, ModelRequest,...
--- +++ @@ -1,3 +1,4 @@+"""Ask user middleware for interactive question-answering during agent execution.""" from __future__ import annotations @@ -27,11 +28,13 @@ class Choice(TypedDict): + """A single choice option for a multiple choice question.""" value: Annotated[str, Field(description="The disp...
https://raw.githubusercontent.com/langchain-ai/deepagents/HEAD/libs/cli/deepagents_cli/ask_user.py
Add standardized docstrings across the file
from typing import Any from langchain.agents.middleware import AgentMiddleware, AgentState from langchain_core.messages import AIMessage, ToolMessage from langgraph.runtime import Runtime from langgraph.types import Overwrite class PatchToolCallsMiddleware(AgentMiddleware): def before_agent(self, state: AgentS...
--- +++ @@ -1,3 +1,4 @@+"""Middleware to patch dangling tool calls in the messages history.""" from typing import Any @@ -8,8 +9,10 @@ class PatchToolCallsMiddleware(AgentMiddleware): + """Middleware to patch dangling tool calls in the messages history.""" def before_agent(self, state: AgentState, ru...
https://raw.githubusercontent.com/langchain-ai/deepagents/HEAD/libs/deepagents/deepagents/middleware/patch_tool_calls.py
Document all public functions with docstrings
import base64 import re import warnings from collections.abc import Callable from dataclasses import dataclass from typing import TYPE_CHECKING, Any, Generic from langgraph.config import get_config if TYPE_CHECKING: from langchain.tools import ToolRuntime from langgraph.store.base import BaseStore, Item from lan...
--- +++ @@ -1,3 +1,4 @@+"""StoreBackend: Adapter for LangGraph's BaseStore (persistent, cross-thread).""" import base64 import re @@ -46,6 +47,7 @@ @dataclass class BackendContext(Generic[StateT, ContextT]): + """Context passed to namespace factory functions.""" state: StateT runtime: "Runtime[Con...
https://raw.githubusercontent.com/langchain-ai/deepagents/HEAD/libs/deepagents/deepagents/backends/store.py