instruction stringclasses 100
values | code stringlengths 78 193k | response stringlengths 259 170k | file stringlengths 59 203 |
|---|---|---|---|
Expand my code with proper documentation strings |
from __future__ import annotations
from datetime import datetime
from typing import TYPE_CHECKING, AsyncIterator, Dict, Optional, Union, overload, Literal
from .asset import Asset
from .enums import EventStatus, EntityType, PrivacyLevel, try_enum
from .mixins import Hashable
from .object import Object, OLDEST_OBJECT... | --- +++ @@ -1,3 +1,26 @@+"""
+The MIT License (MIT)
+
+Copyright (c) 2015-present Rapptz
+
+Permission is hereby granted, free of charge, to any person obtaining a
+copy of this software and associated documentation files (the "Software"),
+to deal in the Software without restriction, including without limitation
+the ... | https://raw.githubusercontent.com/Rapptz/discord.py/HEAD/discord/scheduled_event.py |
Document functions with clear intent |
from __future__ import annotations
import asyncio
import logging
import aiohttp
import yarl
from .state import AutoShardedConnectionState
from .client import Client
from .backoff import ExponentialBackoff
from .gateway import *
from .errors import (
ClientException,
HTTPException,
GatewayNotFound,
C... | --- +++ @@ -1,3 +1,26 @@+"""
+The MIT License (MIT)
+
+Copyright (c) 2015-present Rapptz
+
+Permission is hereby granted, free of charge, to any person obtaining a
+copy of this software and associated documentation files (the "Software"),
+to deal in the Software without restriction, including without limitation
+the ... | https://raw.githubusercontent.com/Rapptz/discord.py/HEAD/discord/shard.py |
Add docstrings including usage examples |
from __future__ import annotations
from typing import TYPE_CHECKING, AsyncIterator, Union, Optional
from .user import User
from .object import Object
from .enums import ReactionType
# fmt: off
__all__ = (
'Reaction',
)
# fmt: on
if TYPE_CHECKING:
from .member import Member
from .types.message import Rea... | --- +++ @@ -1,3 +1,26 @@+"""
+The MIT License (MIT)
+
+Copyright (c) 2015-present Rapptz
+
+Permission is hereby granted, free of charge, to any person obtaining a
+copy of this software and associated documentation files (the "Software"),
+to deal in the Software without restriction, including without limitation
+the ... | https://raw.githubusercontent.com/Rapptz/discord.py/HEAD/discord/reaction.py |
Add docstrings to make code maintainable |
from __future__ import annotations
from typing import Any, Dict, Optional, TYPE_CHECKING, Union
import re
from .asset import Asset, AssetMixin
from . import utils
# fmt: off
__all__ = (
'PartialEmoji',
)
# fmt: on
if TYPE_CHECKING:
from typing_extensions import Self
from .client import Client
from... | --- +++ @@ -1,3 +1,26 @@+"""
+The MIT License (MIT)
+
+Copyright (c) 2015-present Rapptz
+
+Permission is hereby granted, free of charge, to any person obtaining a
+copy of this software and associated documentation files (the "Software"),
+to deal in the Software without restriction, including without limitation
+the ... | https://raw.githubusercontent.com/Rapptz/discord.py/HEAD/discord/partial_emoji.py |
Generate helpful docstrings for debugging |
from __future__ import annotations
import io
import os
from typing import Any, Literal, Optional, TYPE_CHECKING, Tuple, Union
from .errors import DiscordException
from . import utils
from .file import File
import yarl
# fmt: off
__all__ = (
'Asset',
)
# fmt: on
if TYPE_CHECKING:
from typing_extensions impo... | --- +++ @@ -1,3 +1,26 @@+"""
+The MIT License (MIT)
+
+Copyright (c) 2015-present Rapptz
+
+Permission is hereby granted, free of charge, to any person obtaining a
+copy of this software and associated documentation files (the "Software"),
+to deal in the Software without restriction, including without limitation
+the ... | https://raw.githubusercontent.com/Rapptz/discord.py/HEAD/discord/asset.py |
Document this module using docstrings |
from __future__ import annotations
from typing import Any, Dict, Optional, Tuple, Union
import os
import io
from .utils import MISSING
# fmt: off
__all__ = (
'File',
)
# fmt: on
def _strip_spoiler(filename: str) -> Tuple[str, bool]:
stripped = filename
while stripped.startswith('SPOILER_'):
st... | --- +++ @@ -1,3 +1,26 @@+"""
+The MIT License (MIT)
+
+Copyright (c) 2015-present Rapptz
+
+Permission is hereby granted, free of charge, to any person obtaining a
+copy of this software and associated documentation files (the "Software"),
+to deal in the Software without restriction, including without limitation
+the ... | https://raw.githubusercontent.com/Rapptz/discord.py/HEAD/discord/file.py |
Add docstrings explaining edge cases | # -*- coding: utf-8 -*-
from __future__ import annotations
import logging
from typing import Any, Dict, Optional, Generic, TYPE_CHECKING, Sequence, Tuple, Union, List, overload
import asyncio
import datetime
from . import utils
from .enums import try_enum, Locale, InteractionType, InteractionResponseType
from .erro... | --- +++ @@ -1,5 +1,28 @@ # -*- coding: utf-8 -*-
+"""
+The MIT License (MIT)
+
+Copyright (c) 2015-present Rapptz
+
+Permission is hereby granted, free of charge, to any person obtaining a
+copy of this software and associated documentation files (the "Software"),
+to deal in the Software without restriction, includi... | https://raw.githubusercontent.com/Rapptz/discord.py/HEAD/discord/interactions.py |
Add docstrings that explain inputs and outputs |
from __future__ import annotations
from . import utils
from .user import BaseUser
from .asset import Asset
from .enums import TeamMemberRole, TeamMembershipState, try_enum
from typing import TYPE_CHECKING, Optional, List
if TYPE_CHECKING:
from .state import ConnectionState
from .types.team import (
... | --- +++ @@ -1,3 +1,26 @@+"""
+The MIT License (MIT)
+
+Copyright (c) 2015-present Rapptz
+
+Permission is hereby granted, free of charge, to any person obtaining a
+copy of this software and associated documentation files (the "Software"),
+to deal in the Software without restriction, including without limitation
+the ... | https://raw.githubusercontent.com/Rapptz/discord.py/HEAD/discord/team.py |
Help me document legacy Python code |
from __future__ import annotations
import copy
import datetime
from typing import (
Any,
AsyncIterator,
ClassVar,
Collection,
Coroutine,
Dict,
Iterable,
List,
Mapping,
NamedTuple,
Sequence,
Set,
Literal,
Optional,
TYPE_CHECKING,
Tuple,
Union,
ove... | --- +++ @@ -1,3 +1,26 @@+"""
+The MIT License (MIT)
+
+Copyright (c) 2015-present Rapptz
+
+Permission is hereby granted, free of charge, to any person obtaining a
+copy of this software and associated documentation files (the "Software"),
+to deal in the Software without restriction, including without limitation
+the ... | https://raw.githubusercontent.com/Rapptz/discord.py/HEAD/discord/guild.py |
Create simple docstrings for beginners |
from __future__ import annotations
import asyncio
import collections
import collections.abc
import inspect
import importlib.util
import sys
import logging
import types
from typing import (
Any,
Callable,
Mapping,
List,
Dict,
TYPE_CHECKING,
Optional,
Sequence,
TypeVar,
Type,
... | --- +++ @@ -1,3 +1,26 @@+"""
+The MIT License (MIT)
+
+Copyright (c) 2015-present Rapptz
+
+Permission is hereby granted, free of charge, to any person obtaining a
+copy of this software and associated documentation files (the "Software"),
+to deal in the Software without restriction, including without limitation
+the ... | https://raw.githubusercontent.com/Rapptz/discord.py/HEAD/discord/ext/commands/bot.py |
Generate consistent documentation across files |
from __future__ import annotations
from typing import Callable, Any, ClassVar, Dict, Iterator, Set, TYPE_CHECKING, Tuple, Optional, TypedDict, Generic, TypeVar
from .flags import BaseFlags, flag_value, fill_with_flags, alias_flag_value
__all__ = (
'Permissions',
'PermissionOverwrite',
)
if TYPE_CHECKING:
... | --- +++ @@ -1,3 +1,26 @@+"""
+The MIT License (MIT)
+
+Copyright (c) 2015-present Rapptz
+
+Permission is hereby granted, free of charge, to any person obtaining a
+copy of this software and associated documentation files (the "Software"),
+to deal in the Software without restriction, including without limitation
+the ... | https://raw.githubusercontent.com/Rapptz/discord.py/HEAD/discord/permissions.py |
Add docstrings explaining edge cases |
from __future__ import annotations
from typing import TYPE_CHECKING, Any, List, Literal, Optional, Tuple, TypeVar, Dict
import os
from ..utils import MISSING
from ..components import FileUploadComponent
from ..enums import ComponentType
from .item import Item
if TYPE_CHECKING:
from typing_extensions import Self... | --- +++ @@ -1,3 +1,26 @@+"""
+The MIT License (MIT)
+
+Copyright (c) 2015-present Rapptz
+
+Permission is hereby granted, free of charge, to any person obtaining a
+copy of this software and associated documentation files (the "Software"),
+to deal in the Software without restriction, including without limitation
+the ... | https://raw.githubusercontent.com/Rapptz/discord.py/HEAD/discord/ui/file_upload.py |
Annotate my code with docstrings |
from __future__ import annotations
import array
import asyncio
from textwrap import TextWrapper
from typing import (
Any,
AsyncIterable,
AsyncIterator,
Awaitable,
Callable,
Collection,
Coroutine,
Dict,
ForwardRef,
Generic,
Iterable,
Iterator,
List,
Literal,
... | --- +++ @@ -1,3 +1,26 @@+"""
+The MIT License (MIT)
+
+Copyright (c) 2015-present Rapptz
+
+Permission is hereby granted, free of charge, to any person obtaining a
+copy of this software and associated documentation files (the "Software"),
+to deal in the Software without restriction, including without limitation
+the ... | https://raw.githubusercontent.com/Rapptz/discord.py/HEAD/discord/utils.py |
Add structured docstrings to improve clarity |
from __future__ import annotations
from typing import Any, Dict, List, Optional, TYPE_CHECKING, Union
import discord.abc
from .asset import Asset
from .colour import Colour
from .enums import DefaultAvatar
from .flags import PublicUserFlags
from .utils import snowflake_time, _bytes_to_base64_data, MISSING, _get_as_s... | --- +++ @@ -1,3 +1,26 @@+"""
+The MIT License (MIT)
+
+Copyright (c) 2015-present Rapptz
+
+Permission is hereby granted, free of charge, to any person obtaining a
+copy of this software and associated documentation files (the "Software"),
+to deal in the Software without restriction, including without limitation
+the ... | https://raw.githubusercontent.com/Rapptz/discord.py/HEAD/discord/user.py |
Generate docstrings with examples |
from __future__ import annotations
from typing import TYPE_CHECKING, Any, Dict, Generator, List, Literal, Optional, TypeVar, Union, ClassVar
from .item import Item
from .text_display import TextDisplay
from ..enums import ComponentType
from ..utils import get as _utils_get
if TYPE_CHECKING:
from typing_extensio... | --- +++ @@ -1,3 +1,26 @@+"""
+The MIT License (MIT)
+
+Copyright (c) 2015-present Rapptz
+
+Permission is hereby granted, free of charge, to any person obtaining a
+copy of this software and associated documentation files (the "Software"),
+to deal in the Software without restriction, including without limitation
+the ... | https://raw.githubusercontent.com/Rapptz/discord.py/HEAD/discord/ui/section.py |
Generate docstrings for script automation |
from __future__ import annotations
import os
from typing import TYPE_CHECKING, Literal, Optional, Tuple, TypeVar
from ..components import TextInput as TextInputComponent
from ..enums import ComponentType, TextStyle
from ..utils import MISSING, deprecated
from .item import Item
if TYPE_CHECKING:
from typing_exte... | --- +++ @@ -1,3 +1,26 @@+"""
+The MIT License (MIT)
+
+Copyright (c) 2015-present Rapptz
+
+Permission is hereby granted, free of charge, to any person obtaining a
+copy of this software and associated documentation files (the "Software"),
+to deal in the Software without restriction, including without limitation
+the ... | https://raw.githubusercontent.com/Rapptz/discord.py/HEAD/discord/ui/text_input.py |
Add docstrings to make code maintainable |
from __future__ import annotations
from typing import TYPE_CHECKING, List, Literal, Optional, TypeVar, Union
from .item import Item
from ..enums import ComponentType
from ..utils import MISSING
from ..file import File
from ..components import (
MediaGalleryItem,
MediaGalleryComponent,
UnfurledMediaItem,
... | --- +++ @@ -1,3 +1,26 @@+"""
+The MIT License (MIT)
+
+Copyright (c) 2015-present Rapptz
+
+Permission is hereby granted, free of charge, to any person obtaining a
+copy of this software and associated documentation files (the "Software"),
+to deal in the Software without restriction, including without limitation
+the ... | https://raw.githubusercontent.com/Rapptz/discord.py/HEAD/discord/ui/media_gallery.py |
Write documentation strings for class attributes |
from __future__ import annotations
from typing import TYPE_CHECKING, Generator, Literal, Optional, Tuple, TypeVar
from ..components import LabelComponent
from ..enums import ComponentType
from ..utils import MISSING
from .item import Item
if TYPE_CHECKING:
from typing_extensions import Self
from ..types.co... | --- +++ @@ -1,3 +1,26 @@+"""
+The MIT License (MIT)
+
+Copyright (c) 2015-present Rapptz
+
+Permission is hereby granted, free of charge, to any person obtaining a
+copy of this software and associated documentation files (the "Software"),
+to deal in the Software without restriction, including without limitation
+the ... | https://raw.githubusercontent.com/Rapptz/discord.py/HEAD/discord/ui/label.py |
Improve documentation using docstrings |
from __future__ import annotations
from typing import (
Any,
Callable,
ClassVar,
Dict,
Generator,
Iterator,
List,
Optional,
Sequence,
TYPE_CHECKING,
Set,
Tuple,
Type,
Union,
)
from functools import partial
from itertools import groupby
import asyncio
import log... | --- +++ @@ -1,3 +1,26 @@+"""
+The MIT License (MIT)
+
+Copyright (c) 2015-present Rapptz
+
+Permission is hereby granted, free of charge, to any person obtaining a
+copy of this software and associated documentation files (the "Software"),
+to deal in the Software without restriction, including without limitation
+the ... | https://raw.githubusercontent.com/Rapptz/discord.py/HEAD/discord/ui/view.py |
Add docstrings to my Python code |
from __future__ import annotations
from typing import TYPE_CHECKING, Literal, Optional, TypeVar
from .item import Item
from ..components import TextDisplay as TextDisplayComponent
from ..enums import ComponentType
if TYPE_CHECKING:
from typing_extensions import Self
from .view import LayoutView
V = TypeVa... | --- +++ @@ -1,3 +1,26 @@+"""
+The MIT License (MIT)
+
+Copyright (c) 2015-present Rapptz
+
+Permission is hereby granted, free of charge, to any person obtaining a
+copy of this software and associated documentation files (the "Software"),
+to deal in the Software without restriction, including without limitation
+the ... | https://raw.githubusercontent.com/Rapptz/discord.py/HEAD/discord/ui/text_display.py |
Add docstrings that explain inputs and outputs |
from __future__ import annotations
from typing import TYPE_CHECKING, Literal, Optional, TypeVar
from .item import Item
from ..components import SeparatorComponent
from ..enums import SeparatorSpacing, ComponentType
if TYPE_CHECKING:
from typing_extensions import Self
from .view import LayoutView
V = TypeV... | --- +++ @@ -1,3 +1,26 @@+"""
+The MIT License (MIT)
+
+Copyright (c) 2015-present Rapptz
+
+Permission is hereby granted, free of charge, to any person obtaining a
+copy of this software and associated documentation files (the "Software"),
+to deal in the Software without restriction, including without limitation
+the ... | https://raw.githubusercontent.com/Rapptz/discord.py/HEAD/discord/ui/separator.py |
Generate documentation strings for clarity |
from __future__ import annotations
from typing import TYPE_CHECKING, Any, Dict, Literal, Optional, TypeVar, Union
from .item import Item
from ..enums import ComponentType
from ..components import UnfurledMediaItem
from ..file import File
from ..utils import MISSING
if TYPE_CHECKING:
from typing_extensions impor... | --- +++ @@ -1,3 +1,26 @@+"""
+The MIT License (MIT)
+
+Copyright (c) 2015-present Rapptz
+
+Permission is hereby granted, free of charge, to any person obtaining a
+copy of this software and associated documentation files (the "Software"),
+to deal in the Software without restriction, including without limitation
+the ... | https://raw.githubusercontent.com/Rapptz/discord.py/HEAD/discord/ui/thumbnail.py |
Write docstrings for utility functions |
from __future__ import annotations
import copy
from typing import (
TYPE_CHECKING,
Any,
ClassVar,
Dict,
Generator,
List,
Literal,
Optional,
TypeVar,
Union,
)
from .item import Item, ContainedItemCallbackType as ItemCallbackType, _ItemCallback
from .view import _component_to_it... | --- +++ @@ -1,3 +1,26 @@+"""
+The MIT License (MIT)
+
+Copyright (c) 2015-present Rapptz
+
+Permission is hereby granted, free of charge, to any person obtaining a
+copy of this software and associated documentation files (the "Software"),
+to deal in the Software without restriction, including without limitation
+the ... | https://raw.githubusercontent.com/Rapptz/discord.py/HEAD/discord/ui/container.py |
Include argument descriptions in docstrings |
from __future__ import annotations
from typing import (
Any,
List,
Literal,
Optional,
TYPE_CHECKING,
Tuple,
Type,
TypeVar,
Callable,
Union,
Dict,
overload,
Sequence,
)
from contextvars import ContextVar
import copy
import inspect
import os
from .item import Item, Co... | --- +++ @@ -1,3 +1,26 @@+"""
+The MIT License (MIT)
+
+Copyright (c) 2015-present Rapptz
+
+Permission is hereby granted, free of charge, to any person obtaining a
+copy of this software and associated documentation files (the "Software"),
+to deal in the Software without restriction, including without limitation
+the ... | https://raw.githubusercontent.com/Rapptz/discord.py/HEAD/discord/ui/select.py |
Document helper functions with docstrings |
from __future__ import annotations
import select
import socket
import asyncio
import logging
import threading
from typing import TYPE_CHECKING, Optional, Dict, List, Callable, Coroutine, Any, Tuple
from .enums import Enum
from .utils import MISSING, sane_wait_for
from .errors import ConnectionClosed
from .backoff i... | --- +++ @@ -1,3 +1,41 @@+"""
+The MIT License (MIT)
+
+Copyright (c) 2015-present Rapptz
+
+Permission is hereby granted, free of charge, to any person obtaining a
+copy of this software and associated documentation files (the "Software"),
+to deal in the Software without restriction, including without limitation
+the ... | https://raw.githubusercontent.com/Rapptz/discord.py/HEAD/discord/voice_state.py |
Add docstrings for utility scripts |
from __future__ import annotations
import logging
import asyncio
import re
from urllib.parse import quote as urlquote
from typing import Any, Dict, List, Literal, Optional, TYPE_CHECKING, Sequence, Tuple, Union, TypeVar, Type, overload
from contextvars import ContextVar
import weakref
import aiohttp
from .. import... | --- +++ @@ -1,3 +1,26 @@+"""
+The MIT License (MIT)
+
+Copyright (c) 2015-present Rapptz
+
+Permission is hereby granted, free of charge, to any person obtaining a
+copy of this software and associated documentation files (the "Software"),
+to deal in the Software without restriction, including without limitation
+the ... | https://raw.githubusercontent.com/Rapptz/discord.py/HEAD/discord/webhook/async_.py |
Add verbose docstrings with examples |
from __future__ import annotations
import copy
from typing import Callable, Literal, Optional, TYPE_CHECKING, Tuple, TypeVar, Union
import inspect
import os
from .item import Item, ContainedItemCallbackType as ItemCallbackType, _ItemCallback
from ..enums import ButtonStyle, ComponentType
from ..partial_emoji import... | --- +++ @@ -1,3 +1,26 @@+"""
+The MIT License (MIT)
+
+Copyright (c) 2015-present Rapptz
+
+Permission is hereby granted, free of charge, to any person obtaining a
+copy of this software and associated documentation files (the "Software"),
+to deal in the Software without restriction, including without limitation
+the ... | https://raw.githubusercontent.com/Rapptz/discord.py/HEAD/discord/ui/button.py |
Write docstrings for this repository |
# If you're wondering why this is essentially copy pasted from the async_.py
# file, then it's due to needing two separate types to make the typing shenanigans
# a bit easier to write. It's an unfortunate design. Originally, these types were
# merged and an adapter was used to differentiate between the async and sync ... | --- +++ @@ -1,3 +1,26 @@+"""
+The MIT License (MIT)
+
+Copyright (c) 2015-present Rapptz
+
+Permission is hereby granted, free of charge, to any person obtaining a
+copy of this software and associated documentation files (the "Software"),
+to deal in the Software without restriction, including without limitation
+the ... | https://raw.githubusercontent.com/Rapptz/discord.py/HEAD/discord/webhook/sync.py |
Write docstrings for backend logic |
from __future__ import annotations
from typing import TYPE_CHECKING, Any, List, Literal, Optional, Tuple, TypeVar, Dict
import os
from ..utils import MISSING
from ..components import CheckboxGroupComponent, CheckboxComponent, CheckboxGroupOption
from ..enums import ComponentType
from .item import Item
if TYPE_CHECK... | --- +++ @@ -1,3 +1,26 @@+"""
+The MIT License (MIT)
+
+Copyright (c) 2015-present Rapptz
+
+Permission is hereby granted, free of charge, to any person obtaining a
+copy of this software and associated documentation files (the "Software"),
+to deal in the Software without restriction, including without limitation
+the ... | https://raw.githubusercontent.com/Rapptz/discord.py/HEAD/discord/ui/checkbox.py |
Create docstrings for all classes and functions |
from __future__ import annotations
import copy
from typing import (
TYPE_CHECKING,
Any,
Callable,
ClassVar,
Dict,
Generator,
List,
Literal,
Optional,
Sequence,
Type,
TypeVar,
Union,
overload,
)
from .item import Item, ContainedItemCallbackType as ItemCallbackTy... | --- +++ @@ -1,3 +1,26 @@+"""
+The MIT License (MIT)
+
+Copyright (c) 2015-present Rapptz
+
+Permission is hereby granted, free of charge, to any person obtaining a
+copy of this software and associated documentation files (the "Software"),
+to deal in the Software without restriction, including without limitation
+the ... | https://raw.githubusercontent.com/Rapptz/discord.py/HEAD/discord/ui/action_row.py |
Write Python docstrings for this snippet |
from __future__ import annotations
from typing import ClassVar, Dict, Generic, Optional, Tuple, Type, TypeVar, TYPE_CHECKING, Any, Union
import re
from .item import Item
from .._types import ClientT
__all__ = ('DynamicItem',)
BaseT = TypeVar('BaseT', bound='Item[Any]', covariant=True)
if TYPE_CHECKING:
from ty... | --- +++ @@ -1,3 +1,26 @@+"""
+The MIT License (MIT)
+
+Copyright (c) 2015-present Rapptz
+
+Permission is hereby granted, free of charge, to any person obtaining a
+copy of this software and associated documentation files (the "Software"),
+to deal in the Software without restriction, including without limitation
+the ... | https://raw.githubusercontent.com/Rapptz/discord.py/HEAD/discord/ui/dynamic.py |
Insert docstrings into my code |
from __future__ import annotations
import asyncio
import logging
import struct
from typing import Any, Callable, List, Optional, TYPE_CHECKING, Tuple, Union
from . import opus
from .gateway import *
from .errors import ClientException
from .player import AudioPlayer, AudioSource
from .utils import MISSING
from .voic... | --- +++ @@ -1,3 +1,26 @@+"""
+The MIT License (MIT)
+
+Copyright (c) 2015-present Rapptz
+
+Permission is hereby granted, free of charge, to any person obtaining a
+copy of this software and associated documentation files (the "Software"),
+to deal in the Software without restriction, including without limitation
+the ... | https://raw.githubusercontent.com/Rapptz/discord.py/HEAD/discord/voice_client.py |
Write docstrings that follow conventions |
from __future__ import annotations
import copy
from typing import Any, Callable, Coroutine, Dict, Generic, Optional, TYPE_CHECKING, Union, Tuple, Type, TypeVar
from ..interactions import Interaction
from .._types import ClientT
# fmt: off
__all__ = (
'Item',
)
# fmt: on
if TYPE_CHECKING:
from typing_extens... | --- +++ @@ -1,3 +1,26 @@+"""
+The MIT License (MIT)
+
+Copyright (c) 2015-present Rapptz
+
+Permission is hereby granted, free of charge, to any person obtaining a
+copy of this software and associated documentation files (the "Software"),
+to deal in the Software without restriction, including without limitation
+the ... | https://raw.githubusercontent.com/Rapptz/discord.py/HEAD/discord/ui/item.py |
Create docstrings for each class method |
from __future__ import annotations
from typing import TYPE_CHECKING, Any, List, Literal, Optional, Tuple, TypeVar, Dict
import os
from ..utils import MISSING
from ..components import RadioGroupComponent, RadioGroupOption
from ..enums import ComponentType
from .item import Item
if TYPE_CHECKING:
from typing_exte... | --- +++ @@ -1,3 +1,26 @@+"""
+The MIT License (MIT)
+
+Copyright (c) 2015-present Rapptz
+
+Permission is hereby granted, free of charge, to any person obtaining a
+copy of this software and associated documentation files (the "Software"),
+to deal in the Software without restriction, including without limitation
+the ... | https://raw.githubusercontent.com/Rapptz/discord.py/HEAD/discord/ui/radio.py |
Improve documentation using docstrings |
from __future__ import annotations
import asyncio
import logging
import os
from copy import deepcopy
from typing import TYPE_CHECKING, Any, Dict, Optional, Sequence, ClassVar, List
from ..utils import MISSING, find
from .._types import ClientT
from .item import Item
from .view import BaseView
from .select import Bas... | --- +++ @@ -1,3 +1,26 @@+"""
+The MIT License (MIT)
+
+Copyright (c) 2015-present Rapptz
+
+Permission is hereby granted, free of charge, to any person obtaining a
+copy of this software and associated documentation files (the "Software"),
+to deal in the Software without restriction, including without limitation
+the ... | https://raw.githubusercontent.com/Rapptz/discord.py/HEAD/discord/ui/modal.py |
Add docstrings for better understanding |
from __future__ import annotations
from typing import TYPE_CHECKING, Literal, Optional, TypeVar, Union
from .item import Item
from ..components import FileComponent, UnfurledMediaItem
from ..enums import ComponentType
from ..utils import MISSING
from ..file import File as SendableFile
if TYPE_CHECKING:
from ty... | --- +++ @@ -1,3 +1,26 @@+"""
+The MIT License (MIT)
+
+Copyright (c) 2015-present Rapptz
+
+Permission is hereby granted, free of charge, to any person obtaining a
+copy of this software and associated documentation files (the "Software"),
+to deal in the Software without restriction, including without limitation
+the ... | https://raw.githubusercontent.com/Rapptz/discord.py/HEAD/discord/ui/file.py |
Add docstrings for utility scripts |
import httpx
from typing import List, Dict, Any, Optional
from .config import OPENROUTER_API_KEY, OPENROUTER_API_URL
async def query_model(
model: str,
messages: List[Dict[str, str]],
timeout: float = 120.0
) -> Optional[Dict[str, Any]]:
headers = {
"Authorization": f"Bearer {OPENROUTER_API_K... | --- +++ @@ -1,3 +1,4 @@+"""OpenRouter API client for making LLM requests."""
import httpx
from typing import List, Dict, Any, Optional
@@ -9,6 +10,17 @@ messages: List[Dict[str, str]],
timeout: float = 120.0
) -> Optional[Dict[str, Any]]:
+ """
+ Query a single model via OpenRouter API.
+
+ Args:... | https://raw.githubusercontent.com/karpathy/llm-council/HEAD/backend/openrouter.py |
Generate NumPy-style docstrings |
from typing import List, Dict, Any, Tuple
from .openrouter import query_models_parallel, query_model
from .config import COUNCIL_MODELS, CHAIRMAN_MODEL
async def stage1_collect_responses(user_query: str) -> List[Dict[str, Any]]:
messages = [{"role": "user", "content": user_query}]
# Query all models in para... | --- +++ @@ -1,3 +1,4 @@+"""3-stage LLM Council orchestration."""
from typing import List, Dict, Any, Tuple
from .openrouter import query_models_parallel, query_model
@@ -5,6 +6,15 @@
async def stage1_collect_responses(user_query: str) -> List[Dict[str, Any]]:
+ """
+ Stage 1: Collect individual responses ... | https://raw.githubusercontent.com/karpathy/llm-council/HEAD/backend/council.py |
Add docstrings following best practices |
from fastapi import FastAPI, HTTPException
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import StreamingResponse
from pydantic import BaseModel
from typing import List, Dict, Any
import uuid
import json
import asyncio
from . import storage
from .council import run_full_council, generate_c... | --- +++ @@ -1,3 +1,4 @@+"""FastAPI backend for LLM Council."""
from fastapi import FastAPI, HTTPException
from fastapi.middleware.cors import CORSMiddleware
@@ -24,14 +25,17 @@
class CreateConversationRequest(BaseModel):
+ """Request to create a new conversation."""
pass
class SendMessageRequest(Ba... | https://raw.githubusercontent.com/karpathy/llm-council/HEAD/backend/main.py |
Document my Python code with docstrings |
import json
import os
from datetime import datetime
from typing import List, Dict, Any, Optional
from pathlib import Path
from .config import DATA_DIR
def ensure_data_dir():
Path(DATA_DIR).mkdir(parents=True, exist_ok=True)
def get_conversation_path(conversation_id: str) -> str:
return os.path.join(DATA_DI... | --- +++ @@ -1,3 +1,4 @@+"""JSON-based storage for conversations."""
import json
import os
@@ -8,14 +9,25 @@
def ensure_data_dir():
+ """Ensure the data directory exists."""
Path(DATA_DIR).mkdir(parents=True, exist_ok=True)
def get_conversation_path(conversation_id: str) -> str:
+ """Get the file... | https://raw.githubusercontent.com/karpathy/llm-council/HEAD/backend/storage.py |
Generate docstrings for exported functions | # -*- coding: utf-8 -*-
from __future__ import annotations
from typing import List, Optional, TYPE_CHECKING, Union
from .utils import _get_as_snowflake, get, MISSING
from .partial_emoji import _EmojiTag
__all__ = (
'WelcomeChannel',
'WelcomeScreen',
)
if TYPE_CHECKING:
from typing_extensions import Sel... | --- +++ @@ -1,5 +1,28 @@ # -*- coding: utf-8 -*-
+"""
+The MIT License (MIT)
+
+Copyright (c) 2015-present Rapptz
+
+Permission is hereby granted, free of charge, to any person obtaining a
+copy of this software and associated documentation files (the "Software"),
+to deal in the Software without restriction, includi... | https://raw.githubusercontent.com/Rapptz/discord.py/HEAD/discord/welcome_screen.py |
Generate docstrings for script automation |
from __future__ import annotations
from typing import List, Optional, TYPE_CHECKING, Union
from .utils import snowflake_time, _get_as_snowflake, resolve_invite
from .user import BaseUser
from .activity import BaseActivity, Spotify, create_activity
from .invite import Invite
from .enums import Status, try_enum
if TY... | --- +++ @@ -1,3 +1,26 @@+"""
+The MIT License (MIT)
+
+Copyright (c) 2015-present Rapptz
+
+Permission is hereby granted, free of charge, to any person obtaining a
+copy of this software and associated documentation files (the "Software"),
+to deal in the Software without restriction, including without limitation
+the ... | https://raw.githubusercontent.com/Rapptz/discord.py/HEAD/discord/widget.py |
Create documentation for each function signature | # SPDX-License-Identifier: AGPL-3.0-or-later
# Copyright (C) 2025-2026 Philipp Emanuel Weidmann <pew@worldwidemann.com> + contributors
import math
from contextlib import suppress
from dataclasses import dataclass
from typing import Any, Type, cast
import bitsandbytes as bnb
import torch
import torch.linalg as LA
imp... | --- +++ @@ -209,6 +209,15 @@ print(f"* LoRA adapters initialized (targets: {', '.join(target_modules)})")
def _get_quantization_config(self, dtype: str) -> BitsAndBytesConfig | None:
+ """
+ Creates quantization config based on settings.
+
+ Args:
+ dtype: The dtype string... | https://raw.githubusercontent.com/p-e-w/heretic/HEAD/src/heretic/model.py |
Create Google-style docstrings for my code | #!/usr/bin/env python
# Support for Python3.9
from __future__ import annotations
import asyncio
import socket
from typing import TYPE_CHECKING
import aiodns
if TYPE_CHECKING:
from collections.abc import Iterator
class Checker:
def __init__(self, hosts: list[str], nameservers: list[str]) -> None:
s... | --- +++ @@ -1,4 +1,8 @@ #!/usr/bin/env python
+"""
+Created by laramies on 2008-08-21.
+Revised to use aiodns & asyncio on 2019-09-23
+"""
# Support for Python3.9
from __future__ import annotations
@@ -49,6 +53,7 @@ # https://stackoverflow.com/questions/312443/how-do-i-split-a-list-into-equally-sized-chunks
... | https://raw.githubusercontent.com/laramies/theHarvester/HEAD/theHarvester/lib/hostchecker.py |
Write docstrings for algorithm functions | from typing import Any
import aiohttp
from theHarvester.discovery.constants import MissingKey
from theHarvester.lib.core import AsyncFetcher, Core
class SearchBuiltWith:
def __init__(self, word: str):
self.word = word
self.api_key = Core.builtwith_key()
if self.api_key is None:
... | --- +++ @@ -24,6 +24,7 @@ self.analytics: set[str] = set()
async def process(self, proxy: bool = False) -> None:
+ """Get technology stack information for a domain."""
try:
if proxy:
response = await AsyncFetcher.fetch(
@@ -43,6 +44,7 @@ print(f'E... | https://raw.githubusercontent.com/laramies/theHarvester/HEAD/theHarvester/discovery/builtwith.py |
Add docstrings that explain inputs and outputs | import json as _stdlib_json
from types import ModuleType
import aiohttp
from theHarvester.lib.core import AsyncFetcher, Core
json: ModuleType = _stdlib_json
try:
import ujson as _ujson
json = _ujson
except ImportError as e:
print(f"'ujson' not available. Falling back to standard 'json' module. Reason: {... | --- +++ @@ -17,6 +17,9 @@
class SearchRobtex:
+ """
+ Class uses the Robtex passive DNS API to gather subdomains
+ """
def __init__(self, word) -> None:
self.word = word
@@ -27,6 +30,7 @@
@staticmethod
def _safe_parse_json_lines(payload: str) -> list:
+ """Parse JSONL (JSO... | https://raw.githubusercontent.com/laramies/theHarvester/HEAD/theHarvester/discovery/robtex.py |
Add return value explanations in docstrings | import json
from theHarvester.discovery.constants import MissingKey
from theHarvester.lib.core import AsyncFetcher, Core
class SearchNetlas:
def __init__(self, word, limit: int) -> None:
self.word = word
self.totalhosts: list = []
self.totalips: list = []
self.key = Core.netlas_ke... | --- +++ @@ -16,6 +16,10 @@ self.proxy = False
async def do_count(self) -> None:
+ """Counts the total number of subdomains
+
+ :return: None
+ """
api = f'https://app.netlas.io/api/domains_count/?q=*.{self.word}'
headers = {'X-API-Key': self.key}
response =... | https://raw.githubusercontent.com/laramies/theHarvester/HEAD/theHarvester/discovery/netlas.py |
Provide clean and structured docstrings | import random
from theHarvester.lib.core import AsyncFetcher, Core
async def splitter(links):
unique_list = []
name_check = []
for url in links:
tail = url.split('/')[-1]
if len(tail) == 2 or tail == 'zh-cn':
tail = url.split('/')[-2]
name = tail.split('-')
if ... | --- +++ @@ -4,6 +4,13 @@
async def splitter(links):
+ """
+ Method that tries to remove duplicates
+ LinkedinLists pulls a lot of profiles with the same name.
+ This method tries to remove duplicates from the list.
+ :param links: list of links to remove duplicates from
+ :return: a unique-ish lis... | https://raw.githubusercontent.com/laramies/theHarvester/HEAD/theHarvester/discovery/constants.py |
Create documentation strings for testing functions | import json as _stdlib_json
import re
from types import ModuleType
from theHarvester.lib.core import AsyncFetcher, Core
json: ModuleType = _stdlib_json
try:
import ujson as _ujson
json = _ujson
except ImportError:
pass
except Exception:
pass
class SearchGitlab:
def __init__(self, word) -> None... | --- +++ @@ -16,6 +16,9 @@
class SearchGitlab:
+ """
+ Class uses GitLab API to search for domain references in projects and code
+ """
def __init__(self, word) -> None:
self.word = word
@@ -38,6 +41,7 @@ return {}
def _extract_domains_from_text(self, text: str) -> set:
+ ... | https://raw.githubusercontent.com/laramies/theHarvester/HEAD/theHarvester/discovery/gitlabsearch.py |
Write reusable docstrings | from fastapi import APIRouter, Depends, HTTPException
from pydantic import BaseModel
from theHarvester.discovery.additional_apis import AdditionalAPIs
from theHarvester.lib.api.auth import get_api_key
router = APIRouter()
class DomainRequest(BaseModel):
domain: str
api_keys: dict[str, str] | None = None
@... | --- +++ @@ -14,6 +14,7 @@
@router.post('/breaches')
async def get_breaches(request: DomainRequest, api_key: str = Depends(get_api_key)):
+ """Get breach information for a domain using HaveIBeenPwned."""
try:
apis = AdditionalAPIs(request.domain, request.api_keys or {})
await apis._process_h... | https://raw.githubusercontent.com/laramies/theHarvester/HEAD/theHarvester/lib/api/additional_endpoints.py |
Add docstrings to my Python code | from __future__ import annotations
import asyncio
import contextlib
import random
import ssl
from pathlib import Path
from typing import TYPE_CHECKING, Any, ClassVar
import aiohttp
import certifi
# need to import as different name as to not shadow already existing json var in post_fetch
import ujson as json_loader
i... | --- +++ @@ -265,6 +265,9 @@
@staticmethod
def get_supportedengines() -> list[str]:
+ """
+ Returns a list of supported search engines.
+ """
return [
'baidu',
'bevigil',
@@ -468,6 +471,10 @@
@staticmethod
def _get_random_proxy(proxy_dict: dic... | https://raw.githubusercontent.com/laramies/theHarvester/HEAD/theHarvester/lib/core.py |
Write docstrings for this repository | import json as _stdlib_json
from types import ModuleType
from theHarvester.lib.core import AsyncFetcher, Core
json: ModuleType = _stdlib_json
try:
import ujson as _ujson
json = _ujson
except ImportError:
pass
except Exception:
pass
class SearchWindvane:
def __init__(self, word) -> None:
... | --- +++ @@ -15,6 +15,24 @@
class SearchWindvane:
+ """
+ Class uses the Windvane API to gather subdomains and domain intelligence
+ API Documentation: https://windvane.lichoin.com
+
+ The API provides several endpoints:
+ - /ListSubDomain - Subdomain enumeration
+ - /ListDNS - DNS history analysis... | https://raw.githubusercontent.com/laramies/theHarvester/HEAD/theHarvester/discovery/windvane.py |
Fully document this Python code with docstrings | import asyncio
from typing import Any
from theHarvester.discovery.builtwith import SearchBuiltWith
from theHarvester.discovery.haveibeenpwned import SearchHaveIBeenPwned
from theHarvester.discovery.leaklookup import SearchLeakLookup
from theHarvester.discovery.securityscorecard import SearchSecurityScorecard
from theH... | --- +++ @@ -9,6 +9,7 @@
class AdditionalAPIs:
+ """Wrapper class for additional API services."""
def __init__(self, domain: str, api_keys: dict[str, str] | None = None):
self.domain = domain
@@ -38,6 +39,7 @@ self.shodan_data: dict[str, Any] = {}
async def process(self, proxy: bool... | https://raw.githubusercontent.com/laramies/theHarvester/HEAD/theHarvester/discovery/additional_apis.py |
Write proper docstrings for these functions | import aiohttp
from theHarvester.discovery.constants import MissingKey
from theHarvester.lib.core import AsyncFetcher, Core
class SearchLeakLookup:
def __init__(self, word: str):
self.word = word
self.api_key = Core.leaklookup_key()
self.base_url = 'https://leak-lookup.com/api'
se... | --- +++ @@ -18,6 +18,7 @@ self.leak_dates: set[str] = set()
async def process(self, proxy: bool = False) -> None:
+ """Search for leaked credentials associated with an email."""
try:
if proxy:
response = await AsyncFetcher.fetch(
@@ -42,6 +43,7 @@ ... | https://raw.githubusercontent.com/laramies/theHarvester/HEAD/theHarvester/discovery/leaklookup.py |
Add well-formatted docstrings | import aiohttp
from theHarvester.discovery.constants import MissingKey
from theHarvester.lib.core import AsyncFetcher, Core
class SearchSecurityScorecard:
def __init__(self, word: str):
self.word = word
self.api_key = Core.securityscorecard_key()
if self.api_key is None:
raise... | --- +++ @@ -21,6 +21,7 @@ self.ips: list[str] = []
async def process(self, proxy: bool = False) -> None:
+ """Get security scorecard information for a domain."""
try:
if proxy:
response = await AsyncFetcher.fetch(
@@ -38,6 +39,7 @@ print(f'Error i... | https://raw.githubusercontent.com/laramies/theHarvester/HEAD/theHarvester/discovery/securityscorecard.py |
Create documentation strings for testing functions | from typing import Any, ClassVar
from urllib.parse import quote
from theHarvester.discovery.constants import MissingKey
from theHarvester.lib.core import AsyncFetcher, Core
class SearchFullHunt:
BASE_URL = 'https://fullhunt.io/api/v1'
SEARCH_URL = 'https://fullhunt.io/api/v1/search'
# Filter categories... | --- +++ @@ -6,6 +6,60 @@
class SearchFullHunt:
+ """Class to search FullHunt API for domain information
+
+ FullHunt provides various endpoints for attack surface discovery:
+ - Domain Details: Full domain information including hosts, DNS records, ports, etc.
+ - Subdomains: Just the list of subdomains ... | https://raw.githubusercontent.com/laramies/theHarvester/HEAD/theHarvester/discovery/fullhuntsearch.py |
Document helper functions with docstrings |
import asyncio
import json
import logging
import os
import re
from dataclasses import asdict, dataclass, field
from typing import Any
from urllib.parse import urlparse
import aiohttp
from theHarvester.lib.core import AsyncFetcher, Core
# Configure logging
logging.basicConfig(level=logging.INFO, format='%(asctime)s ... | --- +++ @@ -1,3 +1,8 @@+"""
+API endpoint scanner module.
+This module contains the SearchApiEndpoints class that performs comprehensive API endpoint
+scanning, detection, and analysis on target domains with advanced features for security testing.
+"""
import asyncio
import json
@@ -19,6 +24,7 @@
@dataclass
clas... | https://raw.githubusercontent.com/laramies/theHarvester/HEAD/theHarvester/discovery/api_endpoints.py |
Write docstrings describing functionality | import argparse
import os
import traceback
from typing import Any, cast
from fastapi import FastAPI, Header, HTTPException, Query, Request, status
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import HTMLResponse, JSONResponse, RedirectResponse, Response
from pydantic import BaseModel, Fiel... | --- +++ @@ -76,6 +76,11 @@
@app.get('/', response_class=HTMLResponse)
async def root(*, user_agent: str = Header(None)) -> Response:
+ """
+ Root endpoint that displays the theHarvester logo and links to the GitHub repository.
+
+ Also performs basic user agent filtering to redirect suspicious bots.
+ ""... | https://raw.githubusercontent.com/laramies/theHarvester/HEAD/theHarvester/lib/api/api.py |
Add docstrings to improve code quality | import aiohttp
from theHarvester.discovery.constants import MissingKey
from theHarvester.lib.core import AsyncFetcher, Core
class SearchHaveIBeenPwned:
def __init__(self, word: str):
self.word = word
self.api_key = Core.haveibeenpwned_key()
if self.api_key is None:
raise Missi... | --- +++ @@ -21,6 +21,7 @@ self.affected_data: set[str] = set()
async def process(self, proxy: bool = False) -> None:
+ """Search for breaches associated with a domain or email."""
try:
if proxy:
response = await AsyncFetcher.fetch(
@@ -39,6 +40,7 @@ ... | https://raw.githubusercontent.com/laramies/theHarvester/HEAD/theHarvester/discovery/haveibeenpwned.py |
Add concise docstrings to each method | import asyncio
import logging
from urllib.parse import urlparse
from theHarvester.lib.core import AsyncFetcher
class SearchHudsonRock:
def __init__(self, word: str) -> None:
self.word = word.strip().lower()
self.base_url = 'https://cavalier.hudsonrock.com/api/json/v2/osint-tools'
self.to... | --- +++ @@ -6,8 +6,18 @@
class SearchHudsonRock:
+ """Hudson Rock API integration for discovering compromised credentials and stealer logs.
+
+ This class provides comprehensive search capabilities using Hudson Rock's Cavalier API
+ to discover leaked credentials, compromised hosts, and infostealer intelli... | https://raw.githubusercontent.com/laramies/theHarvester/HEAD/theHarvester/discovery/hudsonrocksearch.py |
Add standardized docstrings across the file |
import asyncio
import re
import sys
from collections.abc import Callable
from ipaddress import IPv4Network
from aiodns import DNSResolver
from theHarvester.lib import hostchecker
from theHarvester.lib.core import DATA_DIR
#####################################################################
# DNS FORCE
############... | --- +++ @@ -1,3 +1,10 @@+"""
+============
+DNS Browsing
+============
+
+Explore the space around known hosts & ips for extra catches.
+"""
import asyncio
import re
@@ -49,6 +56,23 @@
def serialize_ip_range(ip: str, netmask: str = '24') -> str:
+ """
+ Serialize a network range in a constant format, 'x.x... | https://raw.githubusercontent.com/laramies/theHarvester/HEAD/theHarvester/discovery/dnssearch.py |
Document this script properly | import argparse
import asyncio
import os
import re
import secrets
import string
import sys
import time
import traceback
from typing import TYPE_CHECKING, Any
import anyio
import netaddr
import ujson
from aiomultiprocess import Pool
from theHarvester.discovery import (
api_endpoints,
baidusearch,
bevigil,
... | --- +++ @@ -82,6 +82,7 @@
def sanitize_for_xml(text: str) -> str:
+ """Sanitize text for safe inclusion in XML documents."""
text = text.replace('&', '&')
text = text.replace('<', '<')
text = text.replace('>', '>')
@@ -105,6 +106,7 @@
async def start(rest_args: argparse.Namespace | N... | https://raw.githubusercontent.com/laramies/theHarvester/HEAD/theHarvester/__main__.py |
Document this code for team use | # --------------------------------------------------------
# Swin Transformer
# Copyright (c) 2021 Microsoft
# Licensed under The MIT License [see LICENSE for details]
# Written by Ze Liu
# --------------------------------------------------------
import io
import os
import time
import torch.distributed as dist
import ... | --- +++ @@ -16,6 +16,12 @@
def has_file_allowed_extension(filename, extensions):
+ """Checks if a file is an allowed extension.
+ Args:
+ filename (string): path to a file
+ Returns:
+ bool: True if the filename ends with a known image extension
+ """
filename_lower = filename.lower()... | https://raw.githubusercontent.com/microsoft/Swin-Transformer/HEAD/data/cached_image_folder.py |
Generate documentation strings for clarity | # --------------------------------------------------------
# Swin Transformer
# Copyright (c) 2021 Microsoft
# Licensed under The MIT License [see LICENSE for details]
# Written by Ze Liu
# --------------------------------------------------------
import torch
import torch.nn as nn
import torch.nn.functional as F
impor... | --- +++ @@ -32,6 +32,14 @@
def window_partition(x, window_size):
+ """
+ Args:
+ x: (B, H, W, C)
+ window_size (int): window size
+
+ Returns:
+ windows: (num_windows*B, window_size, window_size, C)
+ """
B, H, W, C = x.shape
x = x.view(B, H // window_size, window_size, W ... | https://raw.githubusercontent.com/microsoft/Swin-Transformer/HEAD/models/swin_mlp.py |
Write beginner-friendly docstrings | # --------------------------------------------------------
# Swin Transformer MoE
# Copyright (c) 2022 Microsoft
# Licensed under The MIT License [see LICENSE for details]
# Written by Ze Liu
# --------------------------------------------------------
import torch
import torch.nn as nn
import torch.nn.functional as F
i... | --- +++ @@ -102,6 +102,14 @@
def window_partition(x, window_size):
+ """
+ Args:
+ x: (B, H, W, C)
+ window_size (int): window size
+
+ Returns:
+ windows: (num_windows*B, window_size, window_size, C)
+ """
B, H, W, C = x.shape
x = x.view(B, H // window_size, window_size, ... | https://raw.githubusercontent.com/microsoft/Swin-Transformer/HEAD/models/swin_transformer_moe.py |
Create documentation strings for testing functions | # --------------------------------------------------------
# Swin Transformer
# Copyright (c) 2021 Microsoft
# Licensed under The MIT License [see LICENSE for details]
# Written by Ze Liu
# --------------------------------------------------------
import torch
import torch.nn as nn
import torch.utils.checkpoint as chec... | --- +++ @@ -43,6 +43,14 @@
def window_partition(x, window_size):
+ """
+ Args:
+ x: (B, H, W, C)
+ window_size (int): window size
+
+ Returns:
+ windows: (num_windows*B, window_size, window_size, C)
+ """
B, H, W, C = x.shape
x = x.view(B, H // window_size, window_size, W ... | https://raw.githubusercontent.com/microsoft/Swin-Transformer/HEAD/models/swin_transformer.py |
Add docstrings to make code maintainable | # --------------------------------------------------------
# Swin Transformer V2
# Copyright (c) 2022 Microsoft
# Licensed under The MIT License [see LICENSE for details]
# Written by Ze Liu
# --------------------------------------------------------
import torch
import torch.nn as nn
import torch.nn.functional as F
im... | --- +++ @@ -33,6 +33,14 @@
def window_partition(x, window_size):
+ """
+ Args:
+ x: (B, H, W, C)
+ window_size (int): window size
+
+ Returns:
+ windows: (num_windows*B, window_size, window_size, C)
+ """
B, H, W, C = x.shape
x = x.view(B, H // window_size, window_size, W ... | https://raw.githubusercontent.com/microsoft/Swin-Transformer/HEAD/models/swin_transformer_v2.py |
Generate docstrings for exported functions | import json
import os
import gradio as gr
from gradio.components import Component
from typing import Any, Dict, Optional
from src.webui.webui_manager import WebuiManager
from src.utils import config
import logging
from functools import partial
logger = logging.getLogger(__name__)
def update_model_dropdown(llm_provi... | --- +++ @@ -13,6 +13,9 @@
def update_model_dropdown(llm_provider):
+ """
+ Update the model name dropdown with predefined models for the selected provider.
+ """
# Use predefined models for the selected provider
if llm_provider in config.model_names:
return gr.Dropdown(choices=config.mod... | https://raw.githubusercontent.com/browser-use/web-ui/HEAD/src/webui/components/agent_settings_tab.py |
Write Python docstrings for this snippet | import inspect
import logging
import uuid
from datetime import date, datetime, time
from enum import Enum
from typing import Any, Dict, List, Optional, Set, Type, Union, get_type_hints
from browser_use.controller.registry.views import ActionModel
from langchain.tools import BaseTool
from langchain_mcp_adapters.client ... | --- +++ @@ -15,6 +15,15 @@
async def setup_mcp_client_and_tools(mcp_server_config: Dict[str, Any]) -> Optional[MultiServerMCPClient]:
+ """
+ Initializes the MultiServerMCPClient, connects to servers, fetches tools,
+ filters them, and returns a flat list of usable tools and the client instance.
+
+ Ret... | https://raw.githubusercontent.com/browser-use/web-ui/HEAD/src/utils/mcp_client.py |
Annotate my code with docstrings | import pdb
import pyperclip
from typing import Optional, Type, Callable, Dict, Any, Union, Awaitable, TypeVar
from pydantic import BaseModel
from browser_use.agent.views import ActionResult
from browser_use.browser.context import BrowserContext
from browser_use.controller.service import Controller, DoneAction
from bro... | --- +++ @@ -49,6 +49,7 @@ self.mcp_server_config = None
def _register_custom_actions(self):
+ """Register all custom browser actions"""
@self.registry.action(
"When executing tasks, prioritize autonomous completion. However, if you encounter a definitive blocker "
@@ -117,6... | https://raw.githubusercontent.com/browser-use/web-ui/HEAD/src/controller/custom_controller.py |
Write reusable docstrings | import asyncio
import json
import logging
import os
import threading
import uuid
from pathlib import Path
from typing import Any, Dict, List, Optional, TypedDict
from browser_use.browser.browser import BrowserConfig
from langchain_community.tools.file_management import (
ListDirectoryTool,
ReadFileTool,
Wr... | --- +++ @@ -55,6 +55,10 @@ stop_event: threading.Event,
use_vision: bool = False,
) -> Dict[str, Any]:
+ """
+ Runs a single BrowserUseAgent task.
+ Manages browser creation and closing for this specific task.
+ """
if not BrowserUseAgent:
return {
"query": task_... | https://raw.githubusercontent.com/browser-use/web-ui/HEAD/src/agent/deep_research/deep_research_agent.py |
Write docstrings describing functionality | import asyncio
import json
import logging
import os
import uuid
from typing import Any, AsyncGenerator, Dict, Optional
import gradio as gr
# from browser_use.agent.service import Agent
from browser_use.agent.views import (
AgentHistoryList,
AgentOutput,
)
from browser_use.browser.browser import BrowserConfig
... | --- +++ @@ -38,6 +38,7 @@ api_key: Optional[str],
num_ctx: Optional[int] = None,
) -> Optional[BaseChatModel]:
+ """Initializes the LLM based on settings. Returns None if provider/model is missing."""
if not provider or not model_name:
logger.info("LLM Provider or Model Name not speci... | https://raw.githubusercontent.com/browser-use/web-ui/HEAD/src/webui/components/browser_use_agent_tab.py |
Insert docstrings into my code | import gradio as gr
from gradio.components import Component
from functools import partial
from src.webui.webui_manager import WebuiManager
from src.utils import config
import logging
import os
from typing import Any, Dict, AsyncGenerator, Optional, Tuple, Union
import asyncio
import json
from src.agent.deep_research.d... | --- +++ @@ -17,6 +17,7 @@
async def _initialize_llm(provider: Optional[str], model_name: Optional[str], temperature: float,
base_url: Optional[str], api_key: Optional[str], num_ctx: Optional[int] = None):
+ """Initializes the LLM based on settings. Returns None if provider/model is missi... | https://raw.githubusercontent.com/browser-use/web-ui/HEAD/src/webui/components/deep_research_agent_tab.py |
Add docstrings that explain inputs and outputs | # Copyright (c) Microsoft Corporation.
# Licensed under the MIT License.
import torch
import numpy as np
import skimage.io as io
# from face_sdk import FaceDetection
import matplotlib.pyplot as plt
from matplotlib.patches import Rectangle
from skimage.transform import SimilarityTransform
from skimage.transform import... | --- +++ @@ -24,6 +24,12 @@
def calculate_cdf(histogram):
+ """
+ This method calculates the cumulative distribution function
+ :param array histogram: The values of the histogram
+ :return: normalized_cdf: The normalized cumulative distribution function
+ :rtype: array
+ """
# Get the cumulat... | https://raw.githubusercontent.com/microsoft/Bringing-Old-Photos-Back-to-Life/HEAD/Face_Detection/align_warp_back_multiple_dlib_HR.py |
Can you add docstrings to this Python file? | # Copyright (c) Microsoft Corporation.
# Licensed under the MIT License.
import re
import importlib
import torch
from argparse import Namespace
import numpy as np
from PIL import Image
import os
import argparse
import dill as pickle
def save_obj(obj, name):
with open(name, "wb") as f:
pickle.dump(obj, f,... | --- +++ @@ -125,6 +125,11 @@
def natural_keys(text):
+ """
+ alist.sort(key=natural_keys) sorts in human order
+ http://nedbatchelder.com/blog/200712/human_sorting.html
+ (See Toothy's implementation in the comments)
+ """
return [atoi(c) for c in re.split("(\d+)", text)]
@@ -183,6 +188,7 @@... | https://raw.githubusercontent.com/microsoft/Bringing-Old-Photos-Back-to-Life/HEAD/Face_Enhancement/util/util.py |
Generate docstrings with examples | # Copyright (c) Microsoft Corporation.
# Licensed under the MIT License.
import torch
import torch.nn as nn
import torch.nn.functional as F
from detection_models.sync_batchnorm import DataParallelWithCallback
from detection_models.antialiasing import Downsample
class UNet(nn.Module):
def __init__(
self,
... | --- +++ @@ -23,6 +23,28 @@ sync_bn=True,
antialiasing=True,
):
+ """
+ Implementation of
+ U-Net: Convolutional Networks for Biomedical Image Segmentation
+ (Ronneberger et al., 2015)
+ https://arxiv.org/abs/1505.04597
+ Using the default arguments will yield the exact version used
+ ... | https://raw.githubusercontent.com/microsoft/Bringing-Old-Photos-Back-to-Life/HEAD/Global/detection_models/networks.py |
Add docstrings that explain logic | # Copyright (c) Microsoft Corporation.
# Licensed under the MIT License.
import os.path
import io
import zipfile
from data.base_dataset import BaseDataset, get_params, get_transform, normalize
from data.image_folder import make_dataset
from PIL import Image
import torchvision.transforms as transforms
import numpy as n... | --- +++ @@ -15,6 +15,10 @@ from io import BytesIO
def pil_to_np(img_PIL):
+ '''Converts image in PIL format to np.array.
+
+ From W x H x C [0...255] to C x W x H [0..1]
+ '''
ar = np.array(img_PIL)
if len(ar.shape) == 3:
@@ -26,6 +30,10 @@
def np_to_pil(img_np):
+ '''Converts image in np... | https://raw.githubusercontent.com/microsoft/Bringing-Old-Photos-Back-to-Life/HEAD/Global/data/online_dataset_for_old_photos.py |
Add detailed documentation for each class | # Copyright (c) Microsoft Corporation.
# Licensed under the MIT License.
import torch
import numpy as np
import skimage.io as io
# from face_sdk import FaceDetection
import matplotlib.pyplot as plt
from matplotlib.patches import Rectangle
from skimage.transform import SimilarityTransform
from skimage.transform import... | --- +++ @@ -24,6 +24,12 @@
def calculate_cdf(histogram):
+ """
+ This method calculates the cumulative distribution function
+ :param array histogram: The values of the histogram
+ :return: normalized_cdf: The normalized cumulative distribution function
+ :rtype: array
+ """
# Get the cumulat... | https://raw.githubusercontent.com/microsoft/Bringing-Old-Photos-Back-to-Life/HEAD/Face_Detection/align_warp_back_multiple_dlib.py |
Insert docstrings into my code | import json
import os
import time
from pathlib import Path
from typing import List, Dict, Any, Optional
import openai
def load_model_config(model_name: str) -> Dict[str, Any]:
# Try domain directory first
domain_config_path = Path(__file__).parent.parent / 'models_config.json'
# Try project root (parent ... | --- +++ @@ -1,3 +1,7 @@+"""
+Universal LLM calling module
+Supports multiple providers: OpenAI, Anthropic (Claude), Google (Gemini), etc.
+"""
import json
import os
import time
@@ -8,6 +12,23 @@
def load_model_config(model_name: str) -> Dict[str, Any]:
+ """
+ Load model configuration from models_config.js... | https://raw.githubusercontent.com/QwenLM/Qwen-Agent/HEAD/benchmark/deepplanning/travelplanning/agent/call_llm.py |
Add detailed documentation for each class |
import json
import os
import sys
import time
import uuid
from datetime import datetime
from pathlib import Path
from typing import Any, Dict, List, Optional
from concurrent.futures import ThreadPoolExecutor, as_completed
import threading
from threading import Lock
try:
from .call_llm import call_llm
except Import... | --- +++ @@ -1,3 +1,8 @@+"""
+Custom Agent implementation - Framework-independent
+
+Uses universal LLM calling for multiple providers
+"""
import json
import os
@@ -20,6 +25,12 @@
class ShoppingFnAgent:
+ """
+ Lightweight function-calling Agent (shopping scenario):
+ - Loads shopping_tool_schema.json ... | https://raw.githubusercontent.com/QwenLM/Qwen-Agent/HEAD/benchmark/deepplanning/shoppingplanning/agent/shopping_agent.py |
Add docstrings to improve collaboration | import json
import os
import time
from pathlib import Path
from typing import List, Dict, Any, Optional
import openai
def load_model_config(model_name: str) -> Dict[str, Any]:
# Try domain directory first
domain_config_path = Path(__file__).parent.parent / 'models_config.json'
# Try project root (parent ... | --- +++ @@ -1,3 +1,7 @@+"""
+Universal LLM calling module
+Supports OpenAI-compatible APIs
+"""
import json
import os
import time
@@ -8,6 +12,23 @@
def load_model_config(model_name: str) -> Dict[str, Any]:
+ """
+ Load model configuration from models_config.json
+
+ Searches for models_config.json i... | https://raw.githubusercontent.com/QwenLM/Qwen-Agent/HEAD/benchmark/deepplanning/shoppingplanning/agent/call_llm.py |
Annotate my code with docstrings |
import json
import os
import re
import sys
import time
from pathlib import Path
from typing import Dict, Optional
from concurrent.futures import ThreadPoolExecutor, as_completed
from threading import Lock
import openai
# Add parent directory to path to import prompts and call_llm utilities
sys.path.insert(0, str(Pat... | --- +++ @@ -1,3 +1,9 @@+"""
+Convert agent reports to structured JSON format for evaluation
+
+This module uses an LLM to parse the agent's natural language travel plans
+and convert them into structured JSON format required by the evaluation module.
+"""
import json
import os
@@ -19,6 +25,13 @@
# Load environmen... | https://raw.githubusercontent.com/QwenLM/Qwen-Agent/HEAD/benchmark/deepplanning/travelplanning/evaluation/convert_report.py |
Add docstrings to my Python code | import json
import os
import sys
import time
import re
from pathlib import Path
from typing import Dict, Any, List, Optional, Tuple
from concurrent.futures import ThreadPoolExecutor, as_completed
from threading import Lock
try:
from .call_llm import call_llm
except ImportError:
from call_llm import call_llm
... | --- +++ @@ -1,3 +1,7 @@+"""
+Custom Agent implementation - Framework-independent
+Uses universal LLM calling for multiple providers
+"""
import json
import os
import sys
@@ -15,6 +19,12 @@
class ToolsFnAgent:
+ """
+ Lightweight function-calling Agent (framework-independent):
+ - Loads tool schemas from... | https://raw.githubusercontent.com/QwenLM/Qwen-Agent/HEAD/benchmark/deepplanning/travelplanning/agent/tools_fn_agent.py |
Add professional docstrings to my codebase | import json
import os
from typing import Union, Dict, List, Any
from functools import reduce
from base_shopping_tool import BaseShoppingTool, register_tool
from pathlib import Path
@register_tool('filter_by_range')
class FilterByRangeTool(BaseShoppingTool):
def __init__(self, cfg: Dict = None):
super()._... | --- +++ @@ -8,6 +8,11 @@
@register_tool('filter_by_range')
class FilterByRangeTool(BaseShoppingTool):
+ """
+ Tool to filter products by a numeric value range.
+ - If product_ids are provided, filter among those products.
+ - If not provided, filter the entire product database.
+ """
def __init... | https://raw.githubusercontent.com/QwenLM/Qwen-Agent/HEAD/benchmark/deepplanning/shoppingplanning/tools/filter_by_range_tool.py |
Document helper functions with docstrings | import json
from typing import Union, Dict, List, Optional
from base_shopping_tool import BaseShoppingTool, register_tool
from pathlib import Path
@register_tool('get_user_info')
class GetUserInfoTool(BaseShoppingTool):
def __init__(self, cfg: Dict = None):
super().__init__(cfg)
self.users: List[D... | --- +++ @@ -5,6 +5,9 @@
@register_tool('get_user_info')
class GetUserInfoTool(BaseShoppingTool):
+ """
+ Tool for retrieving user information. Can get all users, or a specific user by user_id.
+ """
def __init__(self, cfg: Dict = None):
super().__init__(cfg)
@@ -20,6 +23,7 @@ self._l... | https://raw.githubusercontent.com/QwenLM/Qwen-Agent/HEAD/benchmark/deepplanning/shoppingplanning/tools/get_user_info.py |
Help me add docstrings to my project | import json
import os
from pathlib import Path
from typing import Union, Dict, List
try:
from rank_bm25 import BM25Okapi
except ImportError:
BM25Okapi = None
from base_shopping_tool import BaseShoppingTool, register_tool
# BM25 similarity score threshold; only products with score above this value are returne... | --- +++ @@ -15,8 +15,15 @@
@register_tool('search_products')
class SearchProductsTool(BaseShoppingTool):
+ """
+ Handle open-ended natural language user queries by performing semantic matching
+ using the BM25 algorithm on key product fields.
+ """
def __init__(self, cfg: Dict = None):
+ ""... | https://raw.githubusercontent.com/QwenLM/Qwen-Agent/HEAD/benchmark/deepplanning/shoppingplanning/tools/search_products_tool.py |
Create documentation for each function signature | #!/usr/bin/env python3
import json
import sys
import re
from pathlib import Path
from typing import Dict, Any, Optional
from datetime import datetime
# Add parent directory to path for imports
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
def parse_folder_name(folder_name: str) -> Optional[tuple]:... | --- +++ @@ -1,4 +1,8 @@ #!/usr/bin/env python3
+"""
+Score statistics script
+Calculate total scores for a model across all levels
+"""
import json
import sys
@@ -12,6 +16,11 @@
def parse_folder_name(folder_name: str) -> Optional[tuple]:
+ """
+ Parse folder name to extract model name, difficulty level, a... | https://raw.githubusercontent.com/QwenLM/Qwen-Agent/HEAD/benchmark/deepplanning/shoppingplanning/evaluation/score_statistics.py |
Replace inline comments with docstrings | import os
from typing import Dict, Optional, Union
from .base_travel_tool import BaseTravelTool, register_tool
@register_tool('recommend_restaurants')
class RestaurantRecommendTool(BaseTravelTool):
# Language-specific field mappings
LANG_FIELDS = {
'zh': {
'db_not_loaded': "数据库未加载",
... | --- +++ @@ -1,3 +1,6 @@+"""
+Restaurant Query Tool - Recommend and query restaurant information (Multilingual)
+"""
import os
from typing import Dict, Optional, Union
@@ -6,6 +9,7 @@
@register_tool('recommend_restaurants')
class RestaurantRecommendTool(BaseTravelTool):
+ """Tool for recommending nearby restau... | https://raw.githubusercontent.com/QwenLM/Qwen-Agent/HEAD/benchmark/deepplanning/travelplanning/tools/restaurant_query_tool.py |
Fill in missing docstrings in my code | # Copyright 2023 The Qwen team, Alibaba Group. All rights reserved.
#
# 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... | --- +++ @@ -79,6 +79,7 @@
class Assistant(FnCallAgent):
+ """This is a widely applicable agent integrated with RAG capabilities and function call ability."""
def __init__(self,
function_list: Optional[List[Union[str, Dict, BaseTool]]] = None,
@@ -101,6 +102,13 @@ lang: Liter... | https://raw.githubusercontent.com/QwenLM/Qwen-Agent/HEAD/qwen_agent/agents/assistant.py |
Document this module using docstrings |
# Chinese Version (from TravelBench)
SYSTEM_PROMPT_ZH = """你是一位顶级的旅行规划专家。你的任务是创建一个详尽、可执行且逻辑严谨的旅行计划。
你的工作流程分为两个阶段:
1. 使用工具收集所有必要信息(如航班、路线、价格等)。
2. 信息收集充分后,在 <plan></plan> 标签内生成最终的旅行计划,请严格遵守以下规则。
================================================================
阶段1 – 信息收集阶段
==============================================... | --- +++ @@ -1,3 +1,7 @@+"""
+Prompts for Travel Planning Agent
+Includes both Chinese and English versions
+"""
# Chinese Version (from TravelBench)
SYSTEM_PROMPT_ZH = """你是一位顶级的旅行规划专家。你的任务是创建一个详尽、可执行且逻辑严谨的旅行计划。
@@ -917,6 +921,7 @@
def get_system_prompt(language: str = 'zh') -> str:
+ """Get system prompt ba... | https://raw.githubusercontent.com/QwenLM/Qwen-Agent/HEAD/benchmark/deepplanning/travelplanning/agent/prompts.py |
Add professional docstrings to my codebase | import json
import os
from typing import Union, Dict
from pathlib import Path
from base_shopping_tool import BaseShoppingTool, register_tool
# Province aliases for normalization, including various spellings and abbreviations
PROVINCE_ALIASES = {
'beijing': ['beijing', 'bj', '北京'],
'shanghai': ['shanghai', 'sh'... | --- +++ @@ -86,6 +86,12 @@
@register_tool('calculate_transport_time')
class CalculateTransportTimeTool(BaseShoppingTool):
+ """
+ Tool to estimate logistics delivery time between origin and destination provinces for a product.
+ - Uses a hardcoded matrix of base days between regional districts.
+ - Appli... | https://raw.githubusercontent.com/QwenLM/Qwen-Agent/HEAD/benchmark/deepplanning/shoppingplanning/tools/calculate_transport_time_tool.py |
Add professional docstrings to my codebase |
import re
import csv
import math
import os
from datetime import datetime, time
from pathlib import Path
from typing import Dict, Any, List, Tuple, Optional
# ----------------------
# String Parsing Utilities
# ----------------------
def extract_from_to(text: str) -> Tuple[Optional[str], Optional[str]]:
if not i... | --- +++ @@ -1,3 +1,7 @@+"""
+Utility functions for travel planning evaluation.
+Contains common helper functions for parsing, validation, and data loading.
+"""
import re
import csv
@@ -13,6 +17,7 @@ # ----------------------
def extract_from_to(text: str) -> Tuple[Optional[str], Optional[str]]:
+ """Extract '... | https://raw.githubusercontent.com/QwenLM/Qwen-Agent/HEAD/benchmark/deepplanning/travelplanning/evaluation/utils.py |
Document functions with clear intent | import os
from typing import Dict, Optional, Union
from .base_travel_tool import BaseTravelTool, register_tool
@register_tool('query_hotel_info')
class HotelQueryTool(BaseTravelTool):
# Language-specific field mappings
LANG_FIELDS = {
'zh': {
'db_not_loaded': "数据库未加载",
'n... | --- +++ @@ -1,3 +1,6 @@+"""
+Hotel Query Tool - Query hotel information (Multilingual)
+"""
import os
from typing import Dict, Optional, Union
@@ -6,6 +9,7 @@
@register_tool('query_hotel_info')
class HotelQueryTool(BaseTravelTool):
+ """Tool for querying hotel information (supports zh/en)"""
# Lang... | https://raw.githubusercontent.com/QwenLM/Qwen-Agent/HEAD/benchmark/deepplanning/travelplanning/tools/hotel_query_tool.py |
Add minimal docstrings for each function | import os
from typing import Dict, Optional, Union
from .base_travel_tool import BaseTravelTool, register_tool
@register_tool('query_train_info')
class TrainQueryTool(BaseTravelTool):
# Language-specific field mappings
LANG_FIELDS = {
'zh': {
'segment': lambda idx: f"第{idx}段",
... | --- +++ @@ -1,3 +1,6 @@+"""
+Train Query Tool - Query train ticket information (Multilingual)
+"""
import os
from typing import Dict, Optional, Union
@@ -6,6 +9,7 @@
@register_tool('query_train_info')
class TrainQueryTool(BaseTravelTool):
+ """Tool for querying train ticket information (supports zh/en)"""
... | https://raw.githubusercontent.com/QwenLM/Qwen-Agent/HEAD/benchmark/deepplanning/travelplanning/tools/train_query_tool.py |
Can you add docstrings to this Python file? |
from typing import Dict, Any, Tuple, List, Optional, Union
import re
def eval_hard(plan: Dict[str, Any], meta: Dict[str, Any]) -> Dict[str, Tuple[Optional[bool], Optional[str]]]:
res: Dict[str, Tuple[Optional[bool], Optional[str]]] = {}
# If no hard_constraints field, return default result
if 'hard_... | --- +++ @@ -1,9 +1,23 @@+"""
+Hard Constraint Evaluation Module
+Implements evaluation strategies for each hard constraint type
+"""
from typing import Dict, Any, Tuple, List, Optional, Union
import re
def eval_hard(plan: Dict[str, Any], meta: Dict[str, Any]) -> Dict[str, Tuple[Optional[bool], Optional[str]]]:... | https://raw.githubusercontent.com/QwenLM/Qwen-Agent/HEAD/benchmark/deepplanning/travelplanning/evaluation/constraints_hard.py |
Create docstrings for each class method |
import json
import os
from typing import Union, Dict, List
from base_shopping_tool import BaseShoppingTool, register_tool
from pathlib import Path
@register_tool('filter_by_brand')
class FilterByBrandTool(BaseShoppingTool):
def __init__(self, cfg: Dict = None):
super().__init__(cfg)
self.products... | --- +++ @@ -1,3 +1,6 @@+"""
+Filter products by brand name.
+"""
import json
import os
@@ -7,8 +10,17 @@
@register_tool('filter_by_brand')
class FilterByBrandTool(BaseShoppingTool):
+ """
+ Tool to filter products by brand names.
+ - If product_ids are provided, filter among those products.
+ - If no... | https://raw.githubusercontent.com/QwenLM/Qwen-Agent/HEAD/benchmark/deepplanning/shoppingplanning/tools/filter_by_brand_tool.py |
Create documentation for each function signature |
import json
import os
from abc import ABC, abstractmethod
from typing import Dict, List, Optional, Union, Type
# Pandas lazy import flag (only imported if CSV is used)
PANDAS_AVAILABLE = None
# ========== Tool Schema Loader ==========
def load_tool_schemas(schema_file: str = 'shopping_tool_schema.json') -> Dict[st... | --- +++ @@ -1,3 +1,9 @@+"""
+Base Shopping Tool - Independent Base Tool Class
+
+Framework-agnostic, designed to be compatible with the qwen-agent BaseTool interface.
+Intended to be usable both as a standalone open-source tool and easily integrated into the qwen-agent framework.
+"""
import json
import os
@@ -11,6... | https://raw.githubusercontent.com/QwenLM/Qwen-Agent/HEAD/benchmark/deepplanning/shoppingplanning/tools/base_shopping_tool.py |
Add docstrings for better understanding | import os
from typing import Dict, Optional, Union
from .base_travel_tool import BaseTravelTool, register_tool
@register_tool('query_flight_info')
class FlightQueryTool(BaseTravelTool):
# Language-specific field mappings
LANG_FIELDS = {
'zh': {
'segment': lambda idx: f"第{idx}段",
... | --- +++ @@ -1,3 +1,6 @@+"""
+Flight Query Tool - Query flight information (Multilingual)
+"""
import os
from typing import Dict, Optional, Union
@@ -6,6 +9,7 @@
@register_tool('query_flight_info')
class FlightQueryTool(BaseTravelTool):
+ """Tool for querying flight information (supports zh/en)"""
#... | https://raw.githubusercontent.com/QwenLM/Qwen-Agent/HEAD/benchmark/deepplanning/travelplanning/tools/flight_query_tool.py |
Write proper docstrings for these functions |
import re
import csv
import math
from datetime import datetime, time
from pathlib import Path
from typing import Dict, Any, List, Tuple, Optional
# ----------------------
# Evaluation Dimensions Configuration
# ----------------------
EVALUATION_DIMENSIONS = {
"Route Consistency": {
"weight": 0.125, # 1... | --- +++ @@ -1,3 +1,17 @@+"""
+Commonsense constraints evaluation for travel plans.
+Contains all validation checks for travel plan feasibility and correctness.
+
+Evaluation is organized into 8 dimensions with weighted scoring:
+- Route Consistency (12.5%): valid_trip_duration, closed_loop_route_structure, seamless_int... | https://raw.githubusercontent.com/QwenLM/Qwen-Agent/HEAD/benchmark/deepplanning/travelplanning/evaluation/constraints_commonsense.py |
Create structured documentation for my script |
import argparse
import sys
import time
from pathlib import Path
# Add parent directory to path for imports
sys.path.insert(0, str(Path(__file__).parent))
from agent.call_llm import load_model_config
from evaluation.convert_report import convert_reports
from evaluation.eval_converted import evaluate_plans
from agent.... | --- +++ @@ -1,3 +1,14 @@+"""
+TravelBench Integrated Runner
+
+This script integrates three steps into a single pipeline:
+1. Agent inference (generate trajectories)
+2. Plan parsing/conversion
+3. Evaluation
+
+Usage:
+ python run.py --model qwen-plus --language zh --workers 40
+"""
import argparse
import sys
@... | https://raw.githubusercontent.com/QwenLM/Qwen-Agent/HEAD/benchmark/deepplanning/travelplanning/run.py |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.