instruction
stringclasses
100 values
code
stringlengths
78
193k
response
stringlengths
259
170k
file
stringlengths
59
203
Generate documentation strings for clarity
# 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...
--- +++ @@ -29,6 +29,11 @@ class Agent(ABC): + """A base class for Agent. + + An agent can receive messages and provide response by LLM or Tools. + Different agents have distinct workflows for processing messages and generating responses in the `_run` method. + """ def __init__(self, ...
https://raw.githubusercontent.com/QwenLM/Qwen-Agent/HEAD/qwen_agent/agent.py
Generate docstrings with examples
import os from typing import Dict, Optional, Union from .base_travel_tool import BaseTravelTool, register_tool @register_tool('search_location') class LocationSearchTool(BaseTravelTool): # Language-specific field mappings LANG_FIELDS = { 'zh': { 'db_not_loaded': "数据库未加载", ...
--- +++ @@ -1,3 +1,6 @@+""" +Location Search Tool - Query location coordinates (Multilingual) +""" import os from typing import Dict, Optional, Union @@ -6,6 +9,7 @@ @register_tool('search_location') class LocationSearchTool(BaseTravelTool): + """Tool for querying location latitude and longitude coordinates (...
https://raw.githubusercontent.com/QwenLM/Qwen-Agent/HEAD/benchmark/deepplanning/travelplanning/tools/location_search_tool.py
Add docstrings with type hints explained
# 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...
--- +++ @@ -27,6 +27,10 @@ class GroupChat(Agent, MultiAgentHub): + """This is an agent for multi-agent management. + + This agent can accept a list of agents, manage their speaking order, and output the response of each agent. + """ _VALID_AGENT_SELECTION_METHODS = ['manual', 'round_robin', 'random...
https://raw.githubusercontent.com/QwenLM/Qwen-Agent/HEAD/qwen_agent/agents/group_chat.py
Replace inline comments with docstrings
import json import os import re import time from pathlib import Path from typing import Dict, Any, Tuple, Optional, List from concurrent.futures import ThreadPoolExecutor, as_completed from threading import Lock from .constraints_commonsense import eval_commonsense, EVALUATION_DIMENSIONS from .constraints_hard import...
--- +++ @@ -1,3 +1,7 @@+""" +Evaluation Script for Converted Travel Plans +Evaluates both commonsense and hard constraints with parallel processing +""" import json import os @@ -13,6 +17,23 @@ def calculate_weighted_score(commonsense_results: Dict[str, Tuple[bool, Optional[str]]]) -> Dict[str, Any]: + """ +...
https://raw.githubusercontent.com/QwenLM/Qwen-Agent/HEAD/benchmark/deepplanning/travelplanning/evaluation/eval_converted.py
Add documentation for all methods
import os from typing import Dict, Optional, Union from .base_travel_tool import BaseTravelTool, register_tool @register_tool('query_attraction_details') class AttractionDetailsQueryTool(BaseTravelTool): # Language-specific field mappings LANG_FIELDS = { 'zh': { 'db_not_loaded': "数据库...
--- +++ @@ -1,3 +1,6 @@+""" +Attraction Query Tool - Query and recommend attractions (Multilingual) +""" import os from typing import Dict, Optional, Union @@ -6,6 +9,7 @@ @register_tool('query_attraction_details') class AttractionDetailsQueryTool(BaseTravelTool): + """Tool for querying detailed attraction in...
https://raw.githubusercontent.com/QwenLM/Qwen-Agent/HEAD/benchmark/deepplanning/travelplanning/tools/attraction_query_tool.py
Add docstrings for internal functions
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_size') class FilterBySizeTool(BaseShoppingTool): def __init__(self, cfg: Dict = None): super().__init__(cfg) self.products: L...
--- +++ @@ -6,6 +6,12 @@ @register_tool('filter_by_size') class FilterBySizeTool(BaseShoppingTool): + """ + Tool to filter products by size. + - If product_ids are provided, filter among those products. + - If product_ids are not provided, filter the entire product database. + - Size matching is case-...
https://raw.githubusercontent.com/QwenLM/Qwen-Agent/HEAD/benchmark/deepplanning/shoppingplanning/tools/filter_by_size_tool.py
Add docstrings for utility scripts
#!/usr/bin/env python3 import json import sys from pathlib import Path from typing import Dict, Any, Optional from datetime import datetime def load_shopping_statistics(domain_dir: Path, model_name: str) -> Optional[Dict[str, Any]]: stats_file = domain_dir / "result_report" / f"{model_name}_statistics.json" ...
--- +++ @@ -1,4 +1,8 @@ #!/usr/bin/env python3 +""" +Aggregate results across Shopping and Travel Planning benchmarks +Calculates overall scores by averaging across domains +""" import json import sys @@ -8,6 +12,16 @@ def load_shopping_statistics(domain_dir: Path, model_name: str) -> Optional[Dict[str, Any]]: ...
https://raw.githubusercontent.com/QwenLM/Qwen-Agent/HEAD/benchmark/deepplanning/aggregate_results.py
Document this module using docstrings
import json from typing import Union, Dict from base_shopping_tool import BaseShoppingTool, register_tool from pathlib import Path @register_tool('add_product_to_cart') class AddProductToCartTool(BaseShoppingTool): def __init__(self, cfg: Dict = None): super().__init__(cfg) self.cart_data: Dict = ...
--- +++ @@ -5,6 +5,9 @@ @register_tool('add_product_to_cart') class AddProductToCartTool(BaseShoppingTool): + """ + Tool to add products to cart. Validates product existence and stock availability. + """ def __init__(self, cfg: Dict = None): super().__init__(cfg) @@ -27,6 +30,7 @@ se...
https://raw.githubusercontent.com/QwenLM/Qwen-Agent/HEAD/benchmark/deepplanning/shoppingplanning/tools/add_product_to_cart.py
Add docstrings to existing functions
import json from typing import Union, Dict from base_shopping_tool import BaseShoppingTool, register_tool from pathlib import Path @register_tool('delete_product_from_cart') class DeleteProductFromCartTool(BaseShoppingTool): def __init__(self, cfg: Dict = None): super().__init__(cfg) self.cart_dat...
--- +++ @@ -5,6 +5,9 @@ @register_tool('delete_product_from_cart') class DeleteProductFromCartTool(BaseShoppingTool): + """ + Tool to remove products from cart. Validates product existence and cart presence. + """ def __init__(self, cfg: Dict = None): super().__init__(cfg) @@ -26,6 +29,7 @@ ...
https://raw.githubusercontent.com/QwenLM/Qwen-Agent/HEAD/benchmark/deepplanning/shoppingplanning/tools/delete_product_from_cart.py
Insert docstrings into my code
import json import os from typing import Dict, List, Optional, Union # Import base components from qwen-agent framework from qwen_agent.tools.base import BaseTool, register_tool, TOOL_REGISTRY # Pandas lazy import flag (only imported when CSV is used) PANDAS_AVAILABLE = None # ========== Tool Schema Loader ========...
--- +++ @@ -1,3 +1,6 @@+""" +Base Travel Tool - Extension of qwen-agent BaseTool for travel planning +""" import json import os from typing import Dict, List, Optional, Union @@ -12,6 +15,21 @@ # ========== Tool Schema Loader ========== def load_tool_schemas(schema_file: str = 'tool_schema.json', language: str = ...
https://raw.githubusercontent.com/QwenLM/Qwen-Agent/HEAD/benchmark/deepplanning/travelplanning/tools/base_travel_tool.py
Add docstrings explaining edge cases
import argparse import os import sys import time from pathlib import Path from agent.shopping_agent import run_agent_inference from agent.prompts import prompt_lib sys.path.insert(0, str(Path(__file__).parent)) def parse_args(): parser = argparse.ArgumentParser( description='Run ShoppingBench agent infere...
--- +++ @@ -1,3 +1,11 @@+""" +ShoppingBench Integrated Runner + +This script runs shopping agent inference for different levels. + +Usage: + python run.py --model qwen-plus --level 1 --workers 40 +""" import argparse import os @@ -9,6 +17,7 @@ sys.path.insert(0, str(Path(__file__).parent)) def parse_args(): +...
https://raw.githubusercontent.com/QwenLM/Qwen-Agent/HEAD/benchmark/deepplanning/shoppingplanning/run.py
Document functions with detailed explanations
import json import re from typing import Union, Dict, Tuple, List from base_shopping_tool import BaseShoppingTool, register_tool from pathlib import Path VALID_COUPONS = [ "Cross-store: ¥30 off every ¥300", "Cross-store: ¥60 off every ¥500", "Cross-store: ¥120 off every ¥900", "Cross-store: ¥200 off ev...
--- +++ @@ -19,6 +19,9 @@ @register_tool('add_coupon_to_cart') class AddCouponToCartTool(BaseShoppingTool): + """ + Tool to add coupons to cart. Validates coupon existence, user ownership, and eligibility based on cart total. + """ def __init__(self, cfg: Dict = None): super().__init__(cfg) ...
https://raw.githubusercontent.com/QwenLM/Qwen-Agent/HEAD/benchmark/deepplanning/shoppingplanning/tools/add_coupon_to_cart.py
Create simple docstrings for beginners
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('sort_products') class SortProductsTool(BaseShoppingTool): def __init__(self, cfg: Dict = None): super().__ini...
--- +++ @@ -7,6 +7,12 @@ @register_tool('sort_products') class SortProductsTool(BaseShoppingTool): + """ + A tool to sort a list of products according to a specified attribute. + - If product_ids are provided, only those products are sorted. + - If product_ids are not provided, the entire product databas...
https://raw.githubusercontent.com/QwenLM/Qwen-Agent/HEAD/benchmark/deepplanning/shoppingplanning/tools/sort_product_tool.py
Add inline docstrings for readability
import os from typing import Dict, Optional, Union from .base_travel_tool import BaseTravelTool, register_tool @register_tool('query_road_route_info') class RoadRouteInfoQueryTool(BaseTravelTool): # Language-specific field mappings LANG_FIELDS = { 'zh': { 'db_not_loaded': "数据库未加载", ...
--- +++ @@ -1,3 +1,6 @@+""" +Road Route Query Tool - Query distance and duration between locations (Multilingual) +""" import os from typing import Dict, Optional, Union @@ -6,6 +9,7 @@ @register_tool('query_road_route_info') class RoadRouteInfoQueryTool(BaseTravelTool): + """Tool for querying distance and du...
https://raw.githubusercontent.com/QwenLM/Qwen-Agent/HEAD/benchmark/deepplanning/travelplanning/tools/roadroute_query_tool.py
Document classes and their methods
import json import os from typing import Union, Dict, List from base_shopping_tool import BaseShoppingTool, register_tool from pathlib import Path @register_tool('get_product_details') class GetProductDetailsTool(BaseShoppingTool): def __init__(self, cfg: Dict = None): super().__init__(cfg) self.p...
--- +++ @@ -6,6 +6,9 @@ @register_tool('get_product_details') class GetProductDetailsTool(BaseShoppingTool): + """ + Tool to retrieve complete product details given one or more product_ids. + """ def __init__(self, cfg: Dict = None): super().__init__(cfg) @@ -24,6 +27,7 @@ self._load...
https://raw.githubusercontent.com/QwenLM/Qwen-Agent/HEAD/benchmark/deepplanning/shoppingplanning/tools/get_product_details_tool.py
Add docstrings to incomplete code
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_color') class FilterByColorTool(BaseShoppingTool): def __init__(self, cfg: Dict = None): super().__init__(cfg) self.products:...
--- +++ @@ -6,6 +6,12 @@ @register_tool('filter_by_color') class FilterByColorTool(BaseShoppingTool): + """ + Tool to filter products by color names. + - If product_ids are provided, filter among those products. + - If product_ids are not provided, filter the entire product database. + - Color matchin...
https://raw.githubusercontent.com/QwenLM/Qwen-Agent/HEAD/benchmark/deepplanning/shoppingplanning/tools/filter_by_color_tool.py
Add missing documentation to my Python functions
# 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...
--- +++ @@ -38,12 +38,19 @@ # TODO: merge to retrieval tool class DialogueRetrievalAgent(Assistant): + """This is an agent for super long dialogue.""" def _run(self, messages: List[Message], lang: str = 'en', session_id: str = '', **kwargs) -> Iterato...
https://raw.githubusercontent.com/QwenLM/Qwen-Agent/HEAD/qwen_agent/agents/dialogue_retrieval_agent.py
Create structured documentation for my script
# 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 ap...
--- +++ @@ -25,6 +25,7 @@ class FnCallAgent(Agent): + """This is a widely applicable function call agent integrated with llm and tool use ability.""" def __init__(self, function_list: Optional[List[Union[str, Dict, BaseTool]]] = None, @@ -34,6 +35,18 @@ description: Opti...
https://raw.githubusercontent.com/QwenLM/Qwen-Agent/HEAD/qwen_agent/agents/fncall_agent.py
Generate docstrings with examples
import json import re from typing import Union, Dict, List from pathlib import Path from base_shopping_tool import BaseShoppingTool, register_tool # List of valid coupons VALID_COUPONS = [ "Cross-store: ¥30 off every ¥300", "Cross-store: ¥60 off every ¥500", "Cross-store: ¥120 off every ¥900", "Cross-s...
--- +++ @@ -21,6 +21,9 @@ @register_tool('delete_coupon_from_cart') class DeleteCouponFromCartTool(BaseShoppingTool): + """ + Tool to remove coupons from cart. Updates cart total after removing coupons. + """ def __init__(self, cfg: Dict = None): super().__init__(cfg) self.cart_data: ...
https://raw.githubusercontent.com/QwenLM/Qwen-Agent/HEAD/benchmark/deepplanning/shoppingplanning/tools/delete_coupon_from_cart.py
Include argument descriptions in docstrings
# 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...
--- +++ @@ -31,6 +31,9 @@ def extract_program(result: str, last_only=True): + """ + extract the program after "```python", and before "```" + """ program = '' start = False for line in result.split('\n'): @@ -51,6 +54,7 @@ class TIRMathAgent(FnCallAgent): + """TIR(tool-integrated reas...
https://raw.githubusercontent.com/QwenLM/Qwen-Agent/HEAD/qwen_agent/agents/tir_agent.py
Add inline docstrings for readability
import json import os from typing import Union, Dict, List from base_shopping_tool import BaseShoppingTool, register_tool from pathlib import Path # List of valid coupons VALID_COUPONS = [ "Cross-store: ¥30 off every ¥300", "Cross-store: ¥60 off every ¥500", "Cross-store: ¥120 off every ¥900", "Cross-s...
--- +++ @@ -20,6 +20,11 @@ @register_tool('filter_by_applicable_coupons') class FilterByApplicableCouponsTool(BaseShoppingTool): + """ + Tool to filter products by applicable coupons. + - If product_ids are provided, filter only those products. + - If product_ids are not provided, filter the entire produ...
https://raw.githubusercontent.com/QwenLM/Qwen-Agent/HEAD/benchmark/deepplanning/shoppingplanning/tools/filter_by_applicable_coupons_tool.py
Add docstrings that explain inputs and outputs
import json import os from typing import Union, Dict, List, Optional from base_shopping_tool import BaseShoppingTool, register_tool from pathlib import Path @register_tool('get_cart_info') class GetCartInfoTool(BaseShoppingTool): def __init__(self, cfg: Dict = None): super().__init__(cfg) self.car...
--- +++ @@ -6,6 +6,9 @@ @register_tool('get_cart_info') class GetCartInfoTool(BaseShoppingTool): + """ + Tool for retrieving cart information, including item lists and summary statistics. + """ def __init__(self, cfg: Dict = None): super().__init__(cfg) @@ -21,6 +24,7 @@ self._load_d...
https://raw.githubusercontent.com/QwenLM/Qwen-Agent/HEAD/benchmark/deepplanning/shoppingplanning/tools/get_cart_info.py
Turn comments into proper docstrings
# 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...
--- +++ @@ -30,6 +30,10 @@ class Memory(Agent): + """Memory is special agent for file management. + + By default, this memory can use retrieval tool for RAG. + """ def __init__(self, function_list: Optional[List[Union[str, Dict, BaseTool]]] = None, @@ -37,6 +41,18 @@ ...
https://raw.githubusercontent.com/QwenLM/Qwen-Agent/HEAD/qwen_agent/memory/memory.py
Add concise docstrings to each method
# 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 ap...
--- +++ @@ -59,6 +59,7 @@ class BaseChatModel(ABC): + """The base class of LLM""" @property def support_multimodal_input(self) -> bool: @@ -122,6 +123,20 @@ delta_stream: bool = False, extra_generate_cfg: Optional[Dict] = None, ) -> Union[List[Message], List[Dict], Iterator[List...
https://raw.githubusercontent.com/QwenLM/Qwen-Agent/HEAD/qwen_agent/llm/base.py
Add docstrings to improve code quality
# 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...
--- +++ @@ -27,8 +27,18 @@ class WebUI: + """A Common chatbot application for agent.""" def __init__(self, agent: Union[Agent, MultiAgentHub, List[Agent]], chatbot_config: Optional[dict] = None): + """ + Initialization the chatbot. + + Args: + agent: The agent or a list of ...
https://raw.githubusercontent.com/QwenLM/Qwen-Agent/HEAD/qwen_agent/gui/web_ui.py
Generate docstrings for each module
# 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...
--- +++ @@ -27,6 +27,10 @@ parallel_function_calls: bool = True, function_choice: Union[Literal['auto'], str] = 'auto', **kwargs) -> List[Message]: + """ + Preprocesss the messages and add the functi...
https://raw.githubusercontent.com/QwenLM/Qwen-Agent/HEAD/qwen_agent/llm/fncall_prompts/base_fncall_prompt.py
Document classes and their methods
# 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...
--- +++ @@ -60,6 +60,28 @@ def is_tool_schema(obj: dict) -> bool: + """ + Check if obj is a valid JSON schema describing a tool compatible with OpenAI's tool calling. + Example valid schema: + { + "name": "get_current_weather", + "description": "Get the current weather in a given location", + ...
https://raw.githubusercontent.com/QwenLM/Qwen-Agent/HEAD/qwen_agent/tools/base.py
Create Google-style docstrings for 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 ap...
--- +++ @@ -49,6 +49,7 @@ return full_text def multimodal_typewriter_print(messages: List[dict], text: str = '') -> str: + """Enhanced typewriter print function that displays text and images in Jupyter notebooks.""" try: from PIL import Image @@ -59,6 +60,7 @@ JUPYTER_AVAILABLE = F...
https://raw.githubusercontent.com/QwenLM/Qwen-Agent/HEAD/qwen_agent/utils/output_beautify.py
Document my Python code with docstrings
# 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 ap...
--- +++ @@ -62,12 +62,15 @@ # Image resizing functions (copied from qwen-vl-utils) def round_by_factor(self, number: int, factor: int) -> int: + """Returns the closest integer to 'number' that is divisible by 'factor'.""" return round(number / factor) * factor def ceil_by_factor(self, ...
https://raw.githubusercontent.com/QwenLM/Qwen-Agent/HEAD/qwen_agent/tools/image_zoom_in_qwen3vl.py
Fully document this Python code with docstrings
# 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 ap...
--- +++ @@ -25,6 +25,7 @@ class RefMaterialOutput(BaseModel): + """The knowledge data format output from the retrieval""" url: str text: list @@ -53,6 +54,16 @@ self.max_ref_token: int = self.cfg.get('max_ref_token', DEFAULT_MAX_REF_TOKEN) def call(self, params: Union[str, dict], docs:...
https://raw.githubusercontent.com/QwenLM/Qwen-Agent/HEAD/qwen_agent/tools/search_tools/base_search.py
Add minimal docstrings for each function
# Copyright 2024 Intel Corporation. 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 applicable...
--- +++ @@ -26,6 +26,32 @@ @register_llm('openvino') class OpenVINO(BaseFnCallModel): + """ + OpenVINO Pipeline API. + + To use, you should have the 'optimum[openvino]' python package installed. + + Example export and quantize openvino model by command line: + optimum-cli export openvino --model Q...
https://raw.githubusercontent.com/QwenLM/Qwen-Agent/HEAD/qwen_agent/llm/openvino.py
Create docstrings for reusable components
# 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...
--- +++ @@ -12,6 +12,7 @@ # See the License for the specific language governing permissions and # limitations under the License. +"""Tokenization classes for QWen.""" import base64 import unicodedata @@ -54,6 +55,7 @@ class QWenTokenizer: + """QWen tokenizer.""" vocab_files_names = VOCAB_FILES_NAME...
https://raw.githubusercontent.com/QwenLM/Qwen-Agent/HEAD/qwen_agent/utils/tokenization_qwen.py
Add docstrings following best practices
# 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 ap...
--- +++ @@ -42,6 +42,9 @@ socket.getaddrinfo = _new_getaddrinfo class ImageResult(BaseModel): + """ + Represents an image search result with URL, title, and metadata. + """ id: str = Field(..., description='Unique identifier for the image') title: str = Field(..., description='Title or caption of ...
https://raw.githubusercontent.com/QwenLM/Qwen-Agent/HEAD/qwen_agent/tools/image_search.py
Generate helpful docstrings for debugging
# 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 ap...
--- +++ @@ -170,6 +170,7 @@ del _DOCKER_CONTAINERS[k] def _build_docker_image(self): + """Build Docker image from Dockerfile if not exists""" # Check if image already exists result = subprocess.run( ['docker', 'images', '-q', self.docker_image_name], @@ -443,6 +4...
https://raw.githubusercontent.com/QwenLM/Qwen-Agent/HEAD/qwen_agent/tools/code_interpreter.py
Annotate my code with docstrings
from dataclasses import dataclass, field from typing import Optional @dataclass class ModelArguments: model_name_or_path: str = field( metadata={"help": "Path to pretrained model or model identifier from huggingface.co/models"} ) ptuning_checkpoint: str = field( default=None, metadata={"h...
--- +++ @@ -4,6 +4,9 @@ @dataclass class ModelArguments: + """ + Arguments pertaining to which model/config/tokenizer we are going to fine-tune from. + """ model_name_or_path: str = field( metadata={"help": "Path to pretrained model or model identifier from huggingface.co/models"} @@ -60,6 +...
https://raw.githubusercontent.com/zai-org/ChatGLM2-6B/HEAD/ptuning/arguments.py
Write docstrings for backend logic
# Copyright 2020 The HuggingFace Team. 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 applicabl...
--- +++ @@ -35,6 +35,37 @@ metric_key_prefix: str = "eval", **gen_kwargs ) -> Dict[str, float]: + """ + Run evaluation and returns metrics. + + The calling script will be responsible for providing a method to compute metrics, as they are task-dependent + (pass it to the...
https://raw.githubusercontent.com/zai-org/ChatGLM2-6B/HEAD/ptuning/trainer_seq2seq.py
Document my Python code with docstrings
# Copyright 2024-2025 The Alibaba Wan Team Authors. All rights reserved. import gc import logging import math import os import random import sys import types from contextlib import contextmanager from functools import partial import numpy as np import torch import torch.cuda.amp as amp import torch.distributed as dist...
--- +++ @@ -43,6 +43,29 @@ t5_cpu=False, init_on_cpu=True, ): + r""" + Initializes the image-to-video generation model components. + + Args: + config (EasyDict): + Object containing model parameters initialized from config.py + checkpoint_d...
https://raw.githubusercontent.com/Wan-Video/Wan2.1/HEAD/wan/image2video.py
Generate missing documentation strings
# Copyright 2024-2025 The Alibaba Wan Team Authors. All rights reserved. import gc import logging import math import os import random import sys import types from contextlib import contextmanager from functools import partial import numpy as np import torch import torch.cuda.amp as amp import torch.distributed as dist...
--- +++ @@ -43,6 +43,29 @@ t5_cpu=False, init_on_cpu=True, ): + r""" + Initializes the image-to-video generation model components. + + Args: + config (EasyDict): + Object containing model parameters initialized from config.py + checkpoint_d...
https://raw.githubusercontent.com/Wan-Video/Wan2.1/HEAD/wan/first_last_frame2video.py
Write docstrings that follow conventions
# Copyright 2024-2025 The Alibaba Wan Team Authors. All rights reserved. import math import torch import torch.cuda.amp as amp import torch.nn as nn from diffusers.configuration_utils import ConfigMixin, register_to_config from diffusers.models.modeling_utils import ModelMixin from .attention import flash_attention ...
--- +++ @@ -79,6 +79,10 @@ self.weight = nn.Parameter(torch.ones(dim)) def forward(self, x): + r""" + Args: + x(Tensor): Shape [B, L, C] + """ return self._norm(x.float()).type_as(x) * self.weight def _norm(self, x): @@ -91,6 +95,10 @@ super().__ini...
https://raw.githubusercontent.com/Wan-Video/Wan2.1/HEAD/wan/modules/model.py
Add docstrings to incomplete code
# Copyright 2024-2025 The Alibaba Wan Team Authors. All rights reserved. import gc import logging import math import os import random import sys import time import traceback import types from contextlib import contextmanager from functools import partial import torch import torch.cuda.amp as amp import torch.distribut...
--- +++ @@ -47,6 +47,27 @@ use_usp=False, t5_cpu=False, ): + r""" + Initializes the Wan text-to-video generation model components. + + Args: + config (EasyDict): + Object containing model parameters initialized from config.py + checkpoint_d...
https://raw.githubusercontent.com/Wan-Video/Wan2.1/HEAD/wan/vace.py
Generate docstrings for this script
# Copied from https://github.com/huggingface/diffusers/blob/v0.31.0/src/diffusers/schedulers/scheduling_unipc_multistep.py # Convert unipc for flow matching # Copyright 2024-2025 The Alibaba Wan Team Authors. All rights reserved. import math from typing import List, Optional, Tuple, Union import numpy as np import to...
--- +++ @@ -20,6 +20,57 @@ class FlowUniPCMultistepScheduler(SchedulerMixin, ConfigMixin): + """ + `UniPCMultistepScheduler` is a training-free framework designed for the fast sampling of diffusion models. + + This model inherits from [`SchedulerMixin`] and [`ConfigMixin`]. Check the superclass documentati...
https://raw.githubusercontent.com/Wan-Video/Wan2.1/HEAD/wan/utils/fm_solvers_unipc.py
Fill in missing docstrings in my code
# Copyright 2024-2025 The Alibaba Wan Team Authors. All rights reserved. import logging import torch import torch.cuda.amp as amp import torch.nn as nn import torch.nn.functional as F from einops import rearrange __all__ = [ 'WanVAE', ] CACHE_T = 2 class CausalConv3d(nn.Conv3d): def __init__(self, *args, ...
--- +++ @@ -15,6 +15,9 @@ class CausalConv3d(nn.Conv3d): + """ + Causal 3d convolusion. + """ def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) @@ -54,6 +57,9 @@ class Upsample(nn.Upsample): def forward(self, x): + """ + Fix bfloat16 support for nea...
https://raw.githubusercontent.com/Wan-Video/Wan2.1/HEAD/wan/modules/vae.py
Create docstrings for API functions
# Copyright 2024-2025 The Alibaba Wan Team Authors. All rights reserved. import numpy as np import torch import torch.nn.functional as F import torchvision.transforms.functional as TF from PIL import Image class VaceImageProcessor(object): def __init__(self, downsample=None, seq_len=None): self.downsampl...
--- +++ @@ -35,6 +35,9 @@ return img def _resize_crop(self, img, oh, ow, normalize=True): + """ + Resize, center crop, convert to tensor, and normalize. + """ # resize and crop iw, ih = img.size if iw != ow or ih != oh: @@ -108,6 +111,19 @@ @staticmet...
https://raw.githubusercontent.com/Wan-Video/Wan2.1/HEAD/wan/utils/vace_processor.py
Add documentation for all methods
# Copyright 2024-2025 The Alibaba Wan Team Authors. All rights reserved. import gc import logging import math import os import random import sys import types from contextlib import contextmanager from functools import partial import torch import torch.cuda.amp as amp import torch.distributed as dist from tqdm import t...
--- +++ @@ -39,6 +39,27 @@ use_usp=False, t5_cpu=False, ): + r""" + Initializes the Wan text-to-video generation model components. + + Args: + config (EasyDict): + Object containing model parameters initialized from config.py + checkpoint_d...
https://raw.githubusercontent.com/Wan-Video/Wan2.1/HEAD/wan/text2video.py
Create docstrings for reusable components
# Modified from transformers.models.xlm_roberta.modeling_xlm_roberta # Copyright 2024-2025 The Alibaba Wan Team Authors. All rights reserved. import torch import torch.nn as nn import torch.nn.functional as F __all__ = ['XLMRoberta', 'xlm_roberta_large'] class SelfAttention(nn.Module): def __init__(self, dim, n...
--- +++ @@ -25,6 +25,9 @@ self.dropout = nn.Dropout(dropout) def forward(self, x, mask): + """ + x: [B, L, C]. + """ b, s, c, n, d = *x.size(), self.num_heads, self.head_dim # compute query, key, value @@ -71,6 +74,9 @@ class XLMRoberta(nn.Module): + """ ...
https://raw.githubusercontent.com/Wan-Video/Wan2.1/HEAD/wan/modules/xlm_roberta.py
Provide clean and structured docstrings
# Copied from https://github.com/kq-chen/qwen-vl-utils # Copyright 2024-2025 The Alibaba Wan Team Authors. All rights reserved. from __future__ import annotations import base64 import logging import math import os import sys import time import warnings from functools import lru_cache from io import BytesIO import req...
--- +++ @@ -37,14 +37,17 @@ def round_by_factor(number: int, factor: int) -> int: + """Returns the closest integer to 'number' that is divisible by 'factor'.""" return round(number / factor) * factor def ceil_by_factor(number: int, factor: int) -> int: + """Returns the smallest integer greater than ...
https://raw.githubusercontent.com/Wan-Video/Wan2.1/HEAD/wan/utils/qwen_vl_utils.py
Write docstrings describing functionality
# Copied from https://github.com/huggingface/diffusers/blob/main/src/diffusers/schedulers/scheduling_dpmsolver_multistep.py # Convert dpm solver for flow matching # Copyright 2024-2025 The Alibaba Wan Team Authors. All rights reserved. import inspect import math from typing import List, Optional, Tuple, Union import ...
--- +++ @@ -69,6 +69,60 @@ class FlowDPMSolverMultistepScheduler(SchedulerMixin, ConfigMixin): + """ + `FlowDPMSolverMultistepScheduler` is a fast dedicated high-order solver for diffusion ODEs. + This model inherits from [`SchedulerMixin`] and [`ConfigMixin`]. Check the superclass documentation for the ge...
https://raw.githubusercontent.com/Wan-Video/Wan2.1/HEAD/wan/utils/fm_solvers.py
Create Google-style docstrings for my code
# Copyright 2024-2025 The Alibaba Wan Team Authors. All rights reserved. import torch import torch.cuda.amp as amp from xfuser.core.distributed import ( get_sequence_parallel_rank, get_sequence_parallel_world_size, get_sp_group, ) from xfuser.core.long_ctx_attention import xFuserLongContextAttention from ....
--- +++ @@ -26,6 +26,11 @@ @amp.autocast(enabled=False) def rope_apply(x, grid_sizes, freqs): + """ + x: [B, L, N, C]. + grid_sizes: [B, 3]. + freqs: [M, C // 2]. + """ s, n, c = x.size(1), x.size(2), x.size(3) // 2 # split freqs freqs = freqs.split([c - 2 * (c // 3), c //...
https://raw.githubusercontent.com/Wan-Video/Wan2.1/HEAD/wan/distributed/xdit_context_parallel.py
Generate docstrings for this script
# Copyright 2024-2025 The Alibaba Wan Team Authors. All rights reserved. import json import math import os import random import sys import tempfile from dataclasses import dataclass from http import HTTPStatus from typing import List, Optional, Union import dashscope import torch from PIL import Image try: from f...
--- +++ @@ -219,6 +219,15 @@ retry_times=4, is_vl=False, **kwargs): + ''' + Args: + api_key: The API key for Dash Scope authentication and access to related services. + model_name: Model name, 'qwen-plus' for extending prompts, 'qw...
https://raw.githubusercontent.com/Wan-Video/Wan2.1/HEAD/wan/utils/prompt_extend.py
Help me document legacy Python code
import asyncio import argparse import sys import os # ASCII art banner asciiart = r""" _ ___ _ | | __ _ _ _ __ _| _ ) ___| |_ | |__/ _` | ' \/ _` | _ \/ _ \ _| |____\__,_|_||_\__, |___/\___/\__| |___/ ⭐️ Open Source 开源地址: https://github.com/langbot-app/Lan...
--- +++ @@ -1,3 +1,4 @@+"""LangBot entry point for package execution""" import asyncio import argparse @@ -18,6 +19,7 @@ async def main_entry(loop: asyncio.AbstractEventLoop): + """Main entry point for LangBot""" parser = argparse.ArgumentParser(description='LangBot') parser.add_argument( ...
https://raw.githubusercontent.com/langbot-app/LangBot/HEAD/src/langbot/__main__.py
Write docstrings describing each step
from __future__ import annotations import base64 import quart import re import httpx import uuid import os from .....core import taskmgr from .. import group from langbot_plugin.runtime.plugin.mgr import PluginInstallSource @group.group_class('plugins', '/api/v1/plugins') class PluginsRouterGroup(group.RouterGroup)...
--- +++ @@ -15,6 +15,7 @@ @group.group_class('plugins', '/api/v1/plugins') class PluginsRouterGroup(group.RouterGroup): async def _check_extensions_limit(self) -> str | None: + """Check if extensions limit is reached. Returns error response if limit exceeded, None otherwise.""" limitation = self.a...
https://raw.githubusercontent.com/langbot-app/LangBot/HEAD/src/langbot/pkg/api/http/controller/groups/plugins.py
Write docstrings for this repository
from __future__ import annotations import typing import abc from ..core import app from langbot_plugin.api.entities.builtin.command import context as command_context preregistered_operators: list[typing.Type[CommandOperator]] = [] """预注册命令算子列表。在初始化时,所有算子类会被注册到此列表中。""" def operator_class( name: str, help: ...
--- +++ @@ -19,6 +19,19 @@ privilege: int = 1, # 1为普通用户,2为管理员 parent_class: typing.Type[CommandOperator] = None, ) -> typing.Callable[[typing.Type[CommandOperator]], typing.Type[CommandOperator]]: + """命令类装饰器 + + Args: + name (str): 名称 + help (str, optional): 帮助信息. Defaults to "". + ...
https://raw.githubusercontent.com/langbot-app/LangBot/HEAD/src/langbot/pkg/command/operator.py
Add minimal docstrings for each function
import quart from urllib.parse import unquote from ... import group @group.group_class('knowledge_engines', '/api/v1/knowledge/engines') class KnowledgeEnginesRouterGroup(group.RouterGroup): async def initialize(self) -> None: @self.route('', methods=['GET'], auth_type=group.AuthType.USER_TOKEN_OR_API_KEY...
--- +++ @@ -8,6 +8,11 @@ async def initialize(self) -> None: @self.route('', methods=['GET'], auth_type=group.AuthType.USER_TOKEN_OR_API_KEY) async def list_knowledge_engines() -> quart.Response: + """List all available Knowledge Engines from plugins. + + Returns a list of Kn...
https://raw.githubusercontent.com/langbot-app/LangBot/HEAD/src/langbot/pkg/api/http/controller/groups/knowledge/engines.py
Help me document legacy Python code
import asyncio import base64 import json import time import urllib.parse from typing import Callable import dingtalk_stream # type: ignore import websockets from .EchoHandler import EchoTextHandler from .dingtalkevent import DingTalkEvent import httpx import traceback class DingTalkClient: def __init__( ...
--- +++ @@ -22,6 +22,7 @@ markdown_card: bool, logger: None, ): + """初始化 WebSocket 连接并自动启动""" self.credential = dingtalk_stream.Credential(client_id, client_secret) self.client = dingtalk_stream.DingTalkStreamClient(self.credential) self.key = client_id @@ -56,6 +...
https://raw.githubusercontent.com/langbot-app/LangBot/HEAD/src/langbot/libs/dingtalk_api/api.py
Write docstrings for utility functions
from langbot.libs.wechatpad_api.util.http_util import post_json, get_json class LoginApi: def __init__(self, base_url: str, token: str = None, admin_key: str = None): self.base_url = base_url self.token = token # self.admin_key = admin_key def get_token(self, admin_key, day: int = 365...
--- +++ @@ -3,6 +3,13 @@ class LoginApi: def __init__(self, base_url: str, token: str = None, admin_key: str = None): + """ + + Args: + base_url: 原始路径 + token: token + admin_key: 管理员key + """ self.base_url = base_url self.token = token ...
https://raw.githubusercontent.com/langbot-app/LangBot/HEAD/src/langbot/libs/wechatpad_api/api/login.py
Create docstrings for all classes and functions
from quart import request from .WXBizMsgCrypt3 import WXBizMsgCrypt import base64 import binascii import httpx import traceback from quart import Quart import xml.etree.ElementTree as ET from typing import Callable, Dict, Any from .wecomevent import WecomEvent import langbot_plugin.api.entities.builtin.platform.message...
--- +++ @@ -220,12 +220,27 @@ raise Exception('Failed to send message: ' + str(data)) async def handle_callback_request(self): + """处理回调请求(独立端口模式,使用全局 request)。""" return await self._handle_callback_internal(request) async def handle_unified_webhook(self, req): + """...
https://raw.githubusercontent.com/langbot-app/LangBot/HEAD/src/langbot/libs/wecom_api/api.py
Create structured documentation for my script
from __future__ import annotations import sqlalchemy import argon2 import jwt import datetime import typing import asyncio from ....core import app from ....entity.persistence import user from ....utils import constants from ....entity.errors import account as account_errors class UserService: ap: app.Applicati...
--- +++ @@ -45,6 +45,7 @@ return result_list[0] if result_list is not None and len(result_list) > 0 else None async def get_user_by_space_account_uuid(self, space_account_uuid: str) -> user.User | None: + """Get user by Space account UUID""" result = await self.ap.persistence_mgr.execute_...
https://raw.githubusercontent.com/langbot-app/LangBot/HEAD/src/langbot/pkg/api/http/service/user.py
Document functions with detailed explanations
from typing import Dict, Any, Optional import dingtalk_stream # type: ignore class DingTalkEvent(dict): @staticmethod def from_payload(payload: Dict[str, Any]) -> Optional['DingTalkEvent']: try: event = DingTalkEvent(payload) return event except KeyError: r...
--- +++ @@ -48,10 +48,32 @@ return self.get('conversation_type', '') def __getattr__(self, key: str) -> Optional[Any]: + """ + 允许通过属性访问数据中的任意字段。 + + Args: + key (str): 字段名。 + + Returns: + Optional[Any]: 字段值。 + """ return self.get(key) ...
https://raw.githubusercontent.com/langbot-app/LangBot/HEAD/src/langbot/libs/dingtalk_api/dingtalkevent.py
Write beginner-friendly docstrings
from __future__ import annotations import uuid import datetime import sqlalchemy from ....core import app from ....entity.persistence import monitoring as persistence_monitoring class MonitoringService: ap: app.Application def __init__(self, ap: app.Application) -> None: self.ap = ap # ======...
--- +++ @@ -9,6 +9,7 @@ class MonitoringService: + """Monitoring service""" ap: app.Application @@ -34,6 +35,7 @@ variables: str | None = None, role: str = 'user', ) -> str: + """Record a message""" message_id = str(uuid.uuid4()) message_data = { ...
https://raw.githubusercontent.com/langbot-app/LangBot/HEAD/src/langbot/pkg/api/http/service/monitoring.py
Generate NumPy-style docstrings
import time from quart import request import httpx from quart import Quart from typing import Callable, Dict, Any import langbot_plugin.api.entities.builtin.platform.events as platform_events from .qqofficialevent import QQOfficialEvent import json import traceback from cryptography.hazmat.primitives.asymmetric import ...
--- +++ @@ -34,11 +34,13 @@ self.logger = logger async def check_access_token(self): + """检查access_token是否存在""" if not self.access_token or await self.is_token_expired(): return False return bool(self.access_token and self.access_token.strip()) async def get_a...
https://raw.githubusercontent.com/langbot-app/LangBot/HEAD/src/langbot/libs/qq_official_api/api.py
Add docstrings that explain purpose and usage
from __future__ import annotations from langbot.pkg.utils import httpclient import typing import datetime import time import sqlalchemy from ....core import app from ....entity.persistence import user from ....entity.dto.space_model import SpaceModel class SpaceService: ap: app.Application _credits_cache: ...
--- +++ @@ -12,6 +12,7 @@ class SpaceService: + """Service for interacting with LangBot Space API""" ap: app.Application _credits_cache: typing.Dict[str, typing.Tuple[int, float]] # {user_email: (credits, timestamp)} @@ -21,6 +22,7 @@ self._credits_cache = {} def _get_space_config(sel...
https://raw.githubusercontent.com/langbot-app/LangBot/HEAD/src/langbot/pkg/api/http/service/space.py
Provide clean and structured docstrings
import json import traceback from quart import Quart, jsonify, request from slack_sdk.web.async_client import AsyncWebClient from .slackevent import SlackEvent from typing import Callable import langbot_plugin.api.entities.builtin.platform.events as platform_events class SlackClient: def __init__(self, bot_token:...
--- +++ @@ -28,12 +28,26 @@ self.logger = logger async def handle_callback_request(self): + """处理回调请求(独立端口模式,使用全局 request)""" return await self._handle_callback_internal(request) async def handle_unified_webhook(self, req): + """处理回调请求(统一 webhook 模式,显式传递 request)。 + + ...
https://raw.githubusercontent.com/langbot-app/LangBot/HEAD/src/langbot/libs/slack_api/api.py
Provide docstrings following PEP 257
from __future__ import annotations import uuid import sqlalchemy from ....core import app from ....entity.persistence import model as persistence_model class ModelProviderService: ap: app.Application def __init__(self, ap: app.Application) -> None: self.ap = ap async def get_providers(self) ...
--- +++ @@ -9,6 +9,7 @@ class ModelProviderService: + """Service for managing model providers""" ap: app.Application @@ -16,6 +17,7 @@ self.ap = ap async def get_providers(self) -> list[dict]: + """Get all providers""" result = await self.ap.persistence_mgr.execute_async(s...
https://raw.githubusercontent.com/langbot-app/LangBot/HEAD/src/langbot/pkg/api/http/service/provider.py
Add docstrings to incomplete code
import quart import argon2 import asyncio import traceback from .. import group from .....entity.errors import account as account_errors @group.group_class('user', '/api/v1/user') class UserRouterGroup(group.RouterGroup): async def initialize(self) -> None: @self.route('/init', methods=['GET', 'POST'], a...
--- +++ @@ -99,6 +99,7 @@ @self.route('/space/authorize-url', methods=['GET'], auth_type=group.AuthType.NONE) async def _() -> str: + """Get Space OAuth authorization URL for redirect""" redirect_uri = quart.request.args.get('redirect_uri', '') state = quart.reque...
https://raw.githubusercontent.com/langbot-app/LangBot/HEAD/src/langbot/pkg/api/http/controller/groups/user.py
Write docstrings that follow conventions
from __future__ import annotations import asyncio import json import secrets import time import traceback from typing import Any, Callable, Optional import aiohttp from langbot.libs.wecom_ai_bot_api import wecombotevent from langbot.libs.wecom_ai_bot_api.api import parse_wecom_bot_message from langbot.pkg.platform....
--- +++ @@ -1,3 +1,12 @@+"""WeChat Work AI Bot WebSocket long connection client. + +Implements the WebSocket protocol for receiving messages and sending replies +via a persistent connection to wss://openws.work.weixin.qq.com, as an +alternative to the HTTP callback (webhook) mode. + +Protocol reference: https://develop...
https://raw.githubusercontent.com/langbot-app/LangBot/HEAD/src/langbot/libs/wecom_ai_bot_api/ws_client.py
Document classes and their methods
from typing import Dict, Any, Optional class WecomEvent(dict): @staticmethod def from_payload(payload: Dict[str, Any]) -> Optional['WecomEvent']: try: event = WecomEvent(payload) _ = event.type, event.detail_type # 确保必须字段存在 return event except KeyError: ...
--- +++ @@ -2,9 +2,23 @@ class WecomEvent(dict): + """ + 封装从企业微信收到的事件数据对象(字典),提供属性以获取其中的字段。 + + 除 `type` 和 `detail_type` 属性对于任何事件都有效外,其它属性是否存在(若不存在则返回 `None`)依事件类型不同而不同。 + """ @staticmethod def from_payload(payload: Dict[str, Any]) -> Optional['WecomEvent']: + """ + 从企业微信事件数据构造...
https://raw.githubusercontent.com/langbot-app/LangBot/HEAD/src/langbot/libs/wecom_api/wecomevent.py
Document this script properly
from __future__ import annotations import uuid import json import sqlalchemy from ....core import app from ....entity.persistence import pipeline as persistence_pipeline default_stage_order = [ 'GroupRespondRuleCheckStage', # 群响应规则检查 'BanSessionCheckStage', # 封禁会话检查 'PreContentFilterStage', # 内容过滤前置阶...
--- +++ @@ -160,6 +160,7 @@ await self.ap.pipeline_mgr.remove_pipeline(pipeline_uuid) async def copy_pipeline(self, pipeline_uuid: str) -> str: + """Copy a pipeline with all its configurations""" # Check limitation limitation = self.ap.instance_config.data.get('system', {}).get('...
https://raw.githubusercontent.com/langbot-app/LangBot/HEAD/src/langbot/pkg/api/http/service/pipeline.py
Add docstrings to improve readability
#!/usr/bin/env python # -*- encoding:utf-8 -*- # ------------------------------------------------------------------------ import logging import base64 import random import hashlib import time import struct from Crypto.Cipher import AES import xml.etree.cElementTree as ET import socket from langbot.libs.wecom_ai_bot_a...
--- +++ @@ -1,6 +1,10 @@ #!/usr/bin/env python # -*- encoding:utf-8 -*- +"""对企业微信发送给企业后台的消息加解密示例代码. +@copyright: Copyright (c) 1998-2014 Tencent Inc. + +""" # ------------------------------------------------------------------------ import logging @@ -26,12 +30,21 @@ def throw_exception(message, exception_cla...
https://raw.githubusercontent.com/langbot-app/LangBot/HEAD/src/langbot/libs/wecom_ai_bot_api/WXBizMsgCrypt3.py
Add docstrings to improve collaboration
from __future__ import annotations import datetime import quart from .. import group def parse_iso_datetime(datetime_str: str | None) -> datetime.datetime | None: if not datetime_str: return None # Replace 'Z' with '+00:00' for Python 3.10 compatibility if datetime_str.endswith('Z'): dat...
--- +++ @@ -7,6 +7,7 @@ def parse_iso_datetime(datetime_str: str | None) -> datetime.datetime | None: + """Parse ISO 8601 datetime string, handling 'Z' suffix for UTC timezone""" if not datetime_str: return None # Replace 'Z' with '+00:00' for Python 3.10 compatibility @@ -25,6 +26,7 @@ as...
https://raw.githubusercontent.com/langbot-app/LangBot/HEAD/src/langbot/pkg/api/http/controller/groups/monitoring.py
Generate docstrings with examples
import asyncio import base64 import json import time import traceback import uuid import xml.etree.ElementTree as ET from dataclasses import dataclass, field from typing import Any, Callable, Optional from urllib.parse import unquote import httpx from Crypto.Cipher import AES from quart import Quart, request, Response...
--- +++ @@ -20,6 +20,7 @@ @dataclass class StreamChunk: + """描述单次推送给企业微信的流式片段。""" # 需要返回给企业微信的文本内容 content: str @@ -33,6 +34,7 @@ @dataclass class StreamSession: + """维护一次企业微信流式会话的上下文。""" # 企业微信要求的 stream_id,用于标识后续刷新请求 stream_id: str @@ -63,6 +65,7 @@ class StreamSessionManager: ...
https://raw.githubusercontent.com/langbot-app/LangBot/HEAD/src/langbot/libs/wecom_ai_bot_api/api.py
Generate helpful docstrings for debugging
from typing import Dict, Any, Optional class WecomCSEvent(dict): @staticmethod def from_payload(payload: Dict[str, Any]) -> Optional['WecomCSEvent']: try: event = WecomCSEvent(payload) _ = (event.type,) return event except KeyError: return None ...
--- +++ @@ -2,9 +2,23 @@ class WecomCSEvent(dict): + """ + 封装从企业微信收到的事件数据对象(字典),提供属性以获取其中的字段。 + + 除 `type` 和 `detail_type` 属性对于任何事件都有效外,其它属性是否存在(若不存在则返回 `None`)依事件类型不同而不同。 + """ @staticmethod def from_payload(payload: Dict[str, Any]) -> Optional['WecomCSEvent']: + """ + 从企业微信(客...
https://raw.githubusercontent.com/langbot-app/LangBot/HEAD/src/langbot/libs/wecom_customer_service_api/wecomcsevent.py
Document all public functions with docstrings
from __future__ import annotations import sqlalchemy from ....core import app from ....entity.persistence import rag as persistence_rag class KnowledgeService: ap: app.Application def __init__(self, ap: app.Application) -> None: self.ap = ap async def get_knowledge_bases(self) -> list[dict]: ...
--- +++ @@ -7,6 +7,7 @@ class KnowledgeService: + """知识库服务""" ap: app.Application @@ -14,12 +15,15 @@ self.ap = ap async def get_knowledge_bases(self) -> list[dict]: + """获取所有知识库""" return await self.ap.rag_mgr.get_all_knowledge_base_details() async def get_knowledg...
https://raw.githubusercontent.com/langbot-app/LangBot/HEAD/src/langbot/pkg/api/http/service/knowledge.py
Provide clean and structured docstrings
# 微信公众号的加解密算法与企业微信一样,所以直接使用企业微信的加解密算法文件 import time import traceback from langbot.libs.wecom_api.WXBizMsgCrypt3 import WXBizMsgCrypt import xml.etree.ElementTree as ET from quart import Quart, request import hashlib from typing import Callable from langbot.libs.official_account_api.oaevent import OAEvent import asynci...
--- +++ @@ -60,12 +60,26 @@ self.logger = logger async def handle_callback_request(self): + """处理回调请求(独立端口模式,使用全局 request)。""" return await self._handle_callback_internal(request) async def handle_unified_webhook(self, req): + """处理回调请求(统一 webhook 模式,显式传递 request)。 + + ...
https://raw.githubusercontent.com/langbot-app/LangBot/HEAD/src/langbot/libs/official_account_api/api.py
Insert docstrings into my code
from quart import request from ..wecom_api.WXBizMsgCrypt3 import WXBizMsgCrypt import base64 import binascii import httpx import traceback from quart import Quart import xml.etree.ElementTree as ET from typing import Callable from .wecomcsevent import WecomCSEvent import langbot_plugin.api.entities.builtin.platform.mes...
--- +++ @@ -211,12 +211,27 @@ return data async def handle_callback_request(self): + """处理回调请求(独立端口模式,使用全局 request)。""" return await self._handle_callback_internal(request) async def handle_unified_webhook(self, req): + """处理回调请求(统一 webhook 模式,显式传递 request)。 + + A...
https://raw.githubusercontent.com/langbot-app/LangBot/HEAD/src/langbot/libs/wecom_customer_service_api/api.py
Add verbose docstrings with examples
from __future__ import annotations import uuid import sqlalchemy from langbot_plugin.api.entities.builtin.provider import message as provider_message from ....core import app from ....entity.persistence import model as persistence_model from ....entity.persistence import pipeline as persistence_pipeline from ....pro...
--- +++ @@ -12,6 +12,7 @@ def _parse_provider_api_keys(provider_dict: dict) -> dict: + """Parse api_keys if it's a JSON string""" if isinstance(provider_dict.get('api_keys'), str): import json @@ -29,6 +30,7 @@ self.ap = ap async def get_llm_models(self, include_secret: bool = True...
https://raw.githubusercontent.com/langbot-app/LangBot/HEAD/src/langbot/pkg/api/http/service/model.py
Add detailed docstrings explaining each function
#!/usr/bin/env python # -*- encoding:utf-8 -*- # ------------------------------------------------------------------------ import logging import base64 import random import hashlib import time import struct from Crypto.Cipher import AES import xml.etree.cElementTree as ET import socket from . import ierror """ Cryp...
--- +++ @@ -1,6 +1,10 @@ #!/usr/bin/env python # -*- encoding:utf-8 -*- +"""对企业微信发送给企业后台的消息加解密示例代码. +@copyright: Copyright (c) 1998-2014 Tencent Inc. + +""" # ------------------------------------------------------------------------ import logging @@ -27,12 +31,21 @@ def throw_exception(message, exception_cla...
https://raw.githubusercontent.com/langbot-app/LangBot/HEAD/src/langbot/libs/wecom_api/WXBizMsgCrypt3.py
Write docstrings for backend logic
from typing import Dict, Any, Optional class OAEvent(dict): @staticmethod def from_payload(payload: Dict[str, Any]) -> Optional['OAEvent']: try: event = OAEvent(payload) _ = event.type, event.detail_type # 确保必须字段存在 return event except KeyError: ...
--- +++ @@ -2,9 +2,23 @@ class OAEvent(dict): + """ + 封装从微信公众号收到的事件数据对象(字典),提供属性以获取其中的字段。 + + 除 `type` 和 `detail_type` 属性对于任何事件都有效外,其它属性是否存在(若不存在则返回 `None`)依事件类型不同而不同。 + """ @staticmethod def from_payload(payload: Dict[str, Any]) -> Optional['OAEvent']: + """ + 从微信公众号事件数据构造 `We...
https://raw.githubusercontent.com/langbot-app/LangBot/HEAD/src/langbot/libs/official_account_api/oaevent.py
Generate docstrings with examples
import asyncio import json import httpx import quart import sqlalchemy from ... import group from ......core import taskmgr from ......entity.persistence import metadata as persistence_metadata from langbot_plugin.runtime.plugin.mgr import PluginInstallSource LANGRAG_PLUGIN_AUTHOR = 'langbot-team' LANGRAG_PLUGIN_NAM...
--- +++ @@ -35,6 +35,7 @@ @group.group_class('knowledge/migration', '/api/v1/knowledge/migration') class KnowledgeMigrationRouterGroup(group.RouterGroup): async def _get_migration_flag(self) -> bool: + """Check if rag_plugin_migration_needed flag is set.""" result = await self.ap.persistence_mgr.e...
https://raw.githubusercontent.com/langbot-app/LangBot/HEAD/src/langbot/pkg/api/http/controller/groups/knowledge/migration.py
Add verbose docstrings with examples
from __future__ import annotations from . import model as file_model from .impls import pymodule, json as json_file, yaml as yaml_file class ConfigManager: name: str = None """Config manager name""" description: str = None """Config manager description""" schema: dict = None """Config file...
--- +++ @@ -5,6 +5,7 @@ class ConfigManager: + """Config file manager""" name: str = None """Config manager name""" @@ -41,6 +42,16 @@ async def load_python_module_config(config_name: str, template_name: str, completion: bool = True) -> ConfigManager: + """Load Python module config file + + ...
https://raw.githubusercontent.com/langbot-app/LangBot/HEAD/src/langbot/pkg/config/manager.py
Generate descriptive docstrings automatically
from __future__ import annotations import os from typing import Any from langbot.pkg.utils import constants import yaml import importlib.resources as resources import uuid import time from .. import stage, app from ..bootutils import config def _apply_env_overrides_to_config(cfg: dict) -> dict: def convert_val...
--- +++ @@ -13,8 +13,32 @@ def _apply_env_overrides_to_config(cfg: dict) -> dict: + """Apply environment variable overrides to data/config.yaml + + Environment variables should be uppercase and use __ (double underscore) + to represent nested keys. For example: + - CONCURRENCY__PIPELINE overrides concur...
https://raw.githubusercontent.com/langbot-app/LangBot/HEAD/src/langbot/pkg/core/stages/load_config.py
Add docstrings for utility scripts
# 内容过滤器的抽象类 from __future__ import annotations import abc import typing from ...core import app from . import entities import langbot_plugin.api.entities.builtin.pipeline.query as pipeline_query preregistered_filters: list[typing.Type[ContentFilter]] = [] def filter_class( name: str, ) -> typing.Callable[[typin...
--- +++ @@ -13,6 +13,14 @@ def filter_class( name: str, ) -> typing.Callable[[typing.Type[ContentFilter]], typing.Type[ContentFilter]]: + """Content filter class decorator + + Args: + name (str): Filter name + + Returns: + typing.Callable[[typing.Type[ContentFilter]], typing.Type[ContentFil...
https://raw.githubusercontent.com/langbot-app/LangBot/HEAD/src/langbot/pkg/pipeline/cntfilter/filter.py
Help me document legacy Python code
import sqlalchemy from .. import migration @migration.migration_class(22) class DBMigrateMonitoringUserId(migration.DBMigration): async def _table_exists(self, table_name: str) -> bool: if self.ap.persistence_mgr.db.name == 'postgresql': result = await self.ap.persistence_mgr.execute_async( ...
--- +++ @@ -4,8 +4,14 @@ @migration.migration_class(22) class DBMigrateMonitoringUserId(migration.DBMigration): + """Add user_id and user_name columns to monitoring_sessions table + + This migration adds the missing user_id column and also ensures user_name + column exists (in case migration 21 failed or wa...
https://raw.githubusercontent.com/langbot-app/LangBot/HEAD/src/langbot/pkg/persistence/migrations/dbm022_monitoring_user_name.py
Add clean documentation to messy code
import sqlalchemy from .. import migration @migration.migration_class(20) class DBMigrateKnowledgeEnginePluginArchitecture(migration.DBMigration): async def upgrade(self): has_internal_data = await self._backup_knowledge_bases() has_external_data = await self._check_external_knowledge_bases() ...
--- +++ @@ -4,8 +4,18 @@ @migration.migration_class(20) class DBMigrateKnowledgeEnginePluginArchitecture(migration.DBMigration): + """Migrate to unified Knowledge Engine plugin architecture. + + Changes: + - Backup existing knowledge_bases data to knowledge_bases_backup + - Clear knowledge_bases table an...
https://raw.githubusercontent.com/langbot-app/LangBot/HEAD/src/langbot/pkg/persistence/migrations/dbm020_knowledge_engine_plugin_architecture.py
Add docstrings to make code maintainable
from __future__ import annotations import asyncio import time import typing from dataclasses import dataclass, field import langbot_plugin.api.entities.builtin.platform.message as platform_message import langbot_plugin.api.entities.builtin.platform.events as platform_events import langbot_plugin.api.entities.builtin...
--- +++ @@ -1,3 +1,10 @@+"""Message Aggregator Module + +This module provides message aggregation/debounce functionality. +When users send multiple messages consecutively, the aggregator will wait +for a configurable delay period and merge them into a single message +before processing. +""" from __future__ import an...
https://raw.githubusercontent.com/langbot-app/LangBot/HEAD/src/langbot/pkg/pipeline/aggregator.py
Add minimal docstrings for each function
from __future__ import annotations import abc import typing from ...core import app import langbot_plugin.api.entities.builtin.platform.message as platform_message import langbot_plugin.api.entities.builtin.pipeline.query as pipeline_query preregistered_strategies: list[typing.Type[LongTextStrategy]] = [] def st...
--- +++ @@ -15,6 +15,14 @@ def strategy_class( name: str, ) -> typing.Callable[[typing.Type[LongTextStrategy]], typing.Type[LongTextStrategy]]: + """Long text processing strategy class decorator + + Args: + name (str): Strategy name + + Returns: + typing.Callable[[typing.Type[LongTextStrate...
https://raw.githubusercontent.com/langbot-app/LangBot/HEAD/src/langbot/pkg/pipeline/longtext/strategy.py
Add clean documentation to messy code
import sqlalchemy from .. import migration @migration.migration_class(18) class DBMigrateAddEmojiSupport(migration.DBMigration): async def upgrade(self): # Add emoji field to knowledge_bases await self._add_emoji_to_table('knowledge_bases', '📚') # Add emoji field to external_knowledge_b...
--- +++ @@ -4,8 +4,10 @@ @migration.migration_class(18) class DBMigrateAddEmojiSupport(migration.DBMigration): + """Add emoji field to knowledge_bases, external_knowledge_bases and legacy_pipelines tables""" async def upgrade(self): + """Upgrade""" # Add emoji field to knowledge_bases ...
https://raw.githubusercontent.com/langbot-app/LangBot/HEAD/src/langbot/pkg/persistence/migrations/dbm018_add_emoji_support.py
Can you add docstrings to this Python file?
import uuid as uuid_lib import sqlalchemy from .. import migration @migration.migration_class(16) class DBMigrateModelProviderRefactor(migration.DBMigration): async def upgrade(self): # Step 1: Create model_providers table if not exists await self._create_providers_table() # Step 2: Mig...
--- +++ @@ -6,8 +6,10 @@ @migration.migration_class(16) class DBMigrateModelProviderRefactor(migration.DBMigration): + """Refactor model structure: create providers from existing models and update references""" async def upgrade(self): + """Upgrade""" # Step 1: Create model_providers table ...
https://raw.githubusercontent.com/langbot-app/LangBot/HEAD/src/langbot/pkg/persistence/migrations/dbm016_model_provider_refactor.py
Add standardized docstrings across the file
from __future__ import annotations from ...core import app from .. import stage, entities from . import filter as filter_model, entities as filter_entities from langbot_plugin.api.entities.builtin.provider import message as provider_message import langbot_plugin.api.entities.builtin.platform.message as platform_messa...
--- +++ @@ -16,6 +16,18 @@ @stage.stage_class('PostContentFilterStage') @stage.stage_class('PreContentFilterStage') class ContentFilterStage(stage.PipelineStage): + """内容过滤阶段 + + 前置: + 检查消息是否符合规则,不符合则拦截。 + 改写: + message_chain + + 后置: + 检查AI回复消息是否符合规则,可能进行改写,不符合则拦截。 + 改写...
https://raw.githubusercontent.com/langbot-app/LangBot/HEAD/src/langbot/pkg/pipeline/cntfilter/cntfilter.py
Add docstrings to clarify complex logic
from __future__ import annotations import abc import typing from ...core import app import langbot_plugin.api.entities.builtin.pipeline.query as pipeline_query preregistered_algos: list[typing.Type[ReteLimitAlgo]] = [] def algo_class(name: str): def decorator(cls: typing.Type[ReteLimitAlgo]) -> typing.Type[Ret...
--- +++ @@ -19,6 +19,7 @@ class ReteLimitAlgo(metaclass=abc.ABCMeta): + """限流算法抽象类""" name: str = None @@ -37,6 +38,17 @@ launcher_type: str, launcher_id: typing.Union[int, str], ) -> bool: + """进入处理流程 + + 这个方法对等待是友好的,意味着算法可以实现在这里等待一段时间以控制速率。 + + Args: + ...
https://raw.githubusercontent.com/langbot-app/LangBot/HEAD/src/langbot/pkg/pipeline/ratelimit/algo.py
Add documentation for all methods
from __future__ import annotations import logging logger = logging.getLogger(__name__) # metadata type -> coercion function _COERCE_MAP = { 'integer': lambda v: int(v), 'number': lambda v: float(v), 'float': lambda v: float(v), } def _coerce_bool(v): if isinstance(v, bool): return v if ...
--- +++ @@ -25,6 +25,10 @@ def _coerce_value(value, expected_type: str): + """Convert a single value to the expected type. + + Returns the converted value, or the original value if no conversion needed. + """ if value is None: return value @@ -50,6 +54,16 @@ config: dict, *metadata...
https://raw.githubusercontent.com/langbot-app/LangBot/HEAD/src/langbot/pkg/pipeline/config_coercion.py
Add docstrings to improve collaboration
from __future__ import annotations import os import base64 import time import re from PIL import Image, ImageDraw, ImageFont import functools from .. import strategy as strategy_model import langbot_plugin.api.entities.builtin.pipeline.query as pipeline_query import langbot_plugin.api.entities.builtin.platform.mess...
--- +++ @@ -54,6 +54,11 @@ ] def indexNumber(self, path=''): + """ + 查找字符串中数字所在串中的位置 + :param path:目标字符串 + :return:<class 'list'>: <class 'list'>: [['1', 16], ['2', 35], ['1', 51]] + """ kv = [] nums = [] beforeDatas = re.findall('[\\d]+', pat...
https://raw.githubusercontent.com/langbot-app/LangBot/HEAD/src/langbot/pkg/pipeline/longtext/strategies/image.py
Write docstrings describing each step
from __future__ import annotations import typing import abc from ...core import app import langbot_plugin.api.entities.builtin.pipeline.query as pipeline_query preregistered_truncators: list[typing.Type[Truncator]] = [] def truncator_class( name: str, ) -> typing.Callable[[typing.Type[Truncator]], typing.Type[...
--- +++ @@ -12,6 +12,14 @@ def truncator_class( name: str, ) -> typing.Callable[[typing.Type[Truncator]], typing.Type[Truncator]]: + """截断器类装饰器 + + Args: + name (str): 截断器名称 + + Returns: + typing.Callable[[typing.Type[Truncator]], typing.Type[Truncator]]: 装饰器 + """ def decorator(c...
https://raw.githubusercontent.com/langbot-app/LangBot/HEAD/src/langbot/pkg/pipeline/msgtrun/truncator.py
Auto-generate documentation strings for this file
from __future__ import annotations import traceback import typing import time import json if typing.TYPE_CHECKING: from ..core import app import langbot_plugin.api.entities.builtin.pipeline.query as pipeline_query class MonitoringHelper: @staticmethod async def record_query_start( ap: app....
--- +++ @@ -1,3 +1,8 @@+""" +Monitoring helper for recording events during pipeline execution. +This module provides convenient methods to record monitoring data +without cluttering the main pipeline code. +""" from __future__ import annotations @@ -12,6 +17,7 @@ class MonitoringHelper: + """Helper class fo...
https://raw.githubusercontent.com/langbot-app/LangBot/HEAD/src/langbot/pkg/pipeline/monitoring_helper.py
Add docstrings to meet PEP guidelines
from __future__ import annotations import lark_oapi from lark_oapi.api.im.v1 import CreateImageRequest, CreateImageRequestBody, CreateFileRequest, CreateFileRequestBody import traceback import typing import asyncio import re import base64 import uuid import json import time import datetime import hashlib from Crypto.C...
--- +++ @@ -62,6 +62,7 @@ class LarkMessageConverter(abstract_platform_adapter.AbstractMessageConverter): @staticmethod async def upload_image_to_lark(msg: platform_message.Image, api_client: lark_oapi.Client) -> typing.Optional[str]: + """Upload an image to Lark and return the image_key, or None if up...
https://raw.githubusercontent.com/langbot-app/LangBot/HEAD/src/langbot/pkg/platform/sources/lark.py
Add docstrings to make code maintainable
from __future__ import annotations import asyncio import logging import aiohttp from langbot.pkg.utils import httpclient import uuid from typing import TYPE_CHECKING if TYPE_CHECKING: from ..core import app import langbot_plugin.api.entities.builtin.platform.events as platform_events class WebhookPusher: ...
--- +++ @@ -15,6 +15,7 @@ class WebhookPusher: + """Push bot events to configured webhooks""" ap: app.Application logger: logging.Logger @@ -24,6 +25,11 @@ self.logger = self.ap.logger async def push_person_message(self, event: platform_events.FriendMessage, bot_uuid: str, adapter_name...
https://raw.githubusercontent.com/langbot-app/LangBot/HEAD/src/langbot/pkg/platform/webhook_pusher.py
Create docstrings for each class method
from __future__ import annotations import typing import asyncio import traceback import datetime import pydantic from langbot.libs.wecom_customer_service_api.api import WecomCSClient import langbot_plugin.api.definition.abstract.platform.adapter as abstract_platform_adapter from langbot.libs.wecom_customer_service_ap...
--- +++ @@ -82,6 +82,16 @@ @staticmethod async def target2yiri(event: WecomCSEvent, bot: WecomCSClient = None): + """ + 将 WecomEvent 转换为平台的 FriendMessage 对象。 + + Args: + event (WecomEvent): 企业微信客服事件。 + bot (WecomCSClient): 企业微信客服客户端,用于获取用户信息。 + + Returns: + ...
https://raw.githubusercontent.com/langbot-app/LangBot/HEAD/src/langbot/pkg/platform/sources/wecomcs.py
Add docstrings with type hints explained
from __future__ import annotations import typing import asyncio import traceback import datetime from langbot.libs.wecom_api.api import WecomClient import langbot_plugin.api.definition.abstract.platform.adapter as abstract_platform_adapter from langbot.libs.wecom_api.wecomevent import WecomEvent from ...utils import ...
--- +++ @@ -16,6 +16,17 @@ def split_string_by_bytes(text, limit=2048, encoding='utf-8'): + """ + Splits a string into a list of strings, where each part is at most 'limit' bytes. + + Args: + text (str): The original string to split. + limit (int): The maximum byte size for each split part. +...
https://raw.githubusercontent.com/langbot-app/LangBot/HEAD/src/langbot/pkg/platform/sources/wecom.py
Add structured docstrings to improve clarity
# For connect to plugin runtime. from __future__ import annotations import asyncio from typing import Any import typing import os import sys import httpx import sqlalchemy from async_lru import alru_cache from langbot_plugin.api.entities.builtin.pipeline.query import provider_session from ..core import app from . imp...
--- +++ @@ -32,6 +32,7 @@ class PluginRuntimeConnector: + """Plugin runtime connector""" ap: app.Application @@ -277,6 +278,14 @@ await self.handler.cleanup_plugin_data(plugin_author, plugin_name) async def list_plugins(self, component_kinds: list[str] | None = None) -> list[dict[str,...
https://raw.githubusercontent.com/langbot-app/LangBot/HEAD/src/langbot/pkg/plugin/connector.py
Add docstrings that explain inputs and outputs
from __future__ import annotations import typing from typing import Any import base64 import traceback import sqlalchemy from langbot_plugin.runtime.io import handler from langbot_plugin.runtime.io.connection import Connection from langbot_plugin.entities.io.actions.enums import ( CommonAction, RuntimeToLang...
--- +++ @@ -27,6 +27,13 @@ def _make_rag_error_response(error: Exception, error_type: str, **extra_context) -> handler.ActionResponse: + """Create a clean error response for RAG operations. + + Args: + error: The caught exception. + error_type: A category string like 'EmbeddingError', 'VectorSto...
https://raw.githubusercontent.com/langbot-app/LangBot/HEAD/src/langbot/pkg/plugin/handler.py
Fill in missing docstrings in my code
from __future__ import annotations import abc import typing import time from ...core import app from ...entity.persistence import model as persistence_model import langbot_plugin.api.entities.builtin.resource.tool as resource_tool from . import token import langbot_plugin.api.entities.builtin.pipeline.query as pipeli...
--- +++ @@ -13,6 +13,7 @@ class RuntimeProvider: + """运行时模型提供商""" provider_entity: persistence_model.ModelProvider """提供商数据""" @@ -42,6 +43,7 @@ extra_args: dict[str, typing.Any] = {}, remove_think: bool = False, ) -> provider_message.Message: + """Bridge method for invok...
https://raw.githubusercontent.com/langbot-app/LangBot/HEAD/src/langbot/pkg/provider/modelmgr/requester.py