instruction stringclasses 100
values | code stringlengths 78 193k | response stringlengths 259 170k | file stringlengths 59 203 |
|---|---|---|---|
Generate helpful docstrings for debugging |
from cli_anything.zoom.utils.zoom_backend import api_get, api_post, api_patch
def add_registrant(
meeting_id: int | str,
email: str,
first_name: str = "",
last_name: str = "",
) -> dict:
body = {"email": email}
if first_name:
body["first_name"] = first_name
if last_name:
b... | --- +++ @@ -1,3 +1,11 @@+"""Participant management — add, remove, list registrants for meetings.
+
+Zoom distinguishes between:
+- Registrants: people who registered before the meeting
+- Participants: people who actually attended (available after meeting ends)
+
+This module handles both.
+"""
from cli_anything.zoo... | https://raw.githubusercontent.com/HKUDS/CLI-Anything/HEAD/zoom/agent-harness/cli_anything/zoom/core/participants.py |
Create simple docstrings for beginners |
import os
from pathlib import Path
from cli_anything.zoom.utils.zoom_backend import api_get, api_delete, api_request
def list_recordings(
from_date: str = "",
to_date: str = "",
page_size: int = 30,
) -> dict:
params = {"page_size": min(page_size, 300)}
if from_date:
params["from"] = fro... | --- +++ @@ -1,3 +1,11 @@+"""Recording management — list, download, and delete cloud recordings.
+
+Handles:
+- List recordings for a date range
+- Get recording files for a specific meeting
+- Download recording files
+- Delete recordings
+"""
import os
from pathlib import Path
@@ -10,6 +18,16 @@ to_date: str =... | https://raw.githubusercontent.com/HKUDS/CLI-Anything/HEAD/zoom/agent-harness/cli_anything/zoom/core/recordings.py |
Write docstrings that follow conventions |
import json
import time
import requests
from pathlib import Path
from typing import Any
from urllib.parse import urlencode
# Zoom API base URL
API_BASE = "https://api.zoom.us/v2"
# OAuth endpoints
OAUTH_AUTHORIZE_URL = "https://zoom.us/oauth/authorize"
OAUTH_TOKEN_URL = "https://zoom.us/oauth/token"
# Default conf... | --- +++ @@ -1,3 +1,8 @@+"""Zoom API backend — wraps Zoom REST API v2 via OAuth2.
+
+This module handles all HTTP communication with the Zoom API.
+It is the only module that makes network requests.
+"""
import json
import time
@@ -21,11 +26,13 @@
def get_config_dir() -> Path:
+ """Get or create config direct... | https://raw.githubusercontent.com/HKUDS/CLI-Anything/HEAD/zoom/agent-harness/cli_anything/zoom/utils/zoom_backend.py |
Generate consistent documentation across files |
import copy
from typing import Dict, Any, List, Optional
from cli_anything.obs_studio.utils.obs_utils import unique_name, get_item
TRANSITION_TYPES = {
"cut": {"label": "Cut", "default_duration": 0},
"fade": {"label": "Fade", "default_duration": 300},
"swipe": {"label": "Swipe", "default_duration": 500},... | --- +++ @@ -1,3 +1,4 @@+"""OBS Studio CLI - Transition management."""
import copy
from typing import Dict, Any, List, Optional
@@ -25,6 +26,7 @@ name: Optional[str] = None,
duration: Optional[int] = None,
) -> Dict[str, Any]:
+ """Add a transition."""
if transition_type not in TRANSITION_TYPES:
... | https://raw.githubusercontent.com/HKUDS/CLI-Anything/HEAD/obs-studio/agent-harness/cli_anything/obs_studio/core/transitions.py |
Document functions with detailed explanations |
import json
import os
import copy
from datetime import datetime
from typing import Optional, Dict, Any, List
PROJECT_VERSION = "1.0"
PROFILES = {
"hd1080p30": {
"name": "hd1080p30", "width": 1920, "height": 1080,
"fps_num": 30, "fps_den": 1, "progressive": True,
"dar_num": 16, "dar_den":... | --- +++ @@ -1,3 +1,4 @@+"""Kdenlive CLI - Project management module."""
import json
import os
@@ -78,6 +79,7 @@ dar_num: int = 16,
dar_den: int = 9,
) -> Dict[str, Any]:
+ """Create a new Kdenlive project (JSON format)."""
if profile and profile in PROFILES:
p = PROFILES[profile]
... | https://raw.githubusercontent.com/HKUDS/CLI-Anything/HEAD/kdenlive/agent-harness/cli_anything/kdenlive/core/project.py |
Add verbose docstrings with examples |
import ctypes
import logging
import os
import platform
import sys
from pathlib import Path
logger = logging.getLogger(__name__)
def _get_nvidia_package_lib_dirs() -> list[Path]:
lib_dirs = []
# Find site-packages directories
site_packages_dirs = []
for path in sys.path:
if "site-packages" ... | --- +++ @@ -1,3 +1,14 @@+"""
+CUDA library path setup for nvidia packages installed via pip.
+
+This module must be imported BEFORE any torch or CUDA-dependent libraries are imported.
+It handles locating and loading CUDA libraries (cuDNN, cuBLAS, etc.) from the nvidia
+pip packages.
+
+On Windows: Uses os.add_dll_dire... | https://raw.githubusercontent.com/chidiwilliams/buzz/HEAD/buzz/cuda_setup.py |
Add concise docstrings to each method |
from __future__ import annotations
import json
import click
from .core import diagram as diagram_mod
from .core import export as export_mod
from .core import project as project_mod
from .core.session import Session
from .utils.repl_skin import ReplSkin
_session: Session | None = None
_json_output = False
def ge... | --- +++ @@ -1,3 +1,4 @@+"""Stateful CLI harness for Mermaid Live Editor."""
from __future__ import annotations
@@ -41,6 +42,7 @@ @click.option("--project", "project_path", default=None, help="Open a Mermaid project file")
@click.pass_context
def cli(ctx, json_mode: bool, project_path: str | None) -> None:
+ "... | https://raw.githubusercontent.com/HKUDS/CLI-Anything/HEAD/mermaid/agent-harness/cli_anything/mermaid/mermaid_cli.py |
Add docstrings including usage examples |
import os
from typing import Optional
from lxml import etree
from ..utils import mlt_xml
from ..utils.time import parse_time_input, frames_to_timecode
from .session import Session
def _get_track_playlist(session: Session, track_index: int) -> etree._Element:
tractor = session.get_main_tractor()
tracks = mlt... | --- +++ @@ -1,3 +1,4 @@+"""Timeline operations: tracks, clips, trimming, splitting, moving."""
import os
from typing import Optional
@@ -9,6 +10,7 @@
def _get_track_playlist(session: Session, track_index: int) -> etree._Element:
+ """Get the playlist element for a track by its index."""
tractor = sessio... | https://raw.githubusercontent.com/HKUDS/CLI-Anything/HEAD/shotcut/agent-harness/cli_anything/shotcut/core/timeline.py |
Create docstrings for all classes and functions |
import webbrowser
import http.server
import threading
from urllib.parse import urlparse, parse_qs
from cli_anything.zoom.utils.zoom_backend import (
load_config, save_config, load_tokens, save_tokens,
get_authorize_url, exchange_code, get_current_user,
CONFIG_DIR,
)
def setup_oauth(client_id: str, clien... | --- +++ @@ -1,3 +1,12 @@+"""OAuth2 authentication flow for Zoom API.
+
+Handles:
+- OAuth app setup (client_id, client_secret, redirect_uri)
+- Browser-based authorization flow
+- Token exchange and persistence
+- Token refresh
+- Auth status checking
+"""
import webbrowser
import http.server
@@ -13,6 +22,16 @@
d... | https://raw.githubusercontent.com/HKUDS/CLI-Anything/HEAD/zoom/agent-harness/cli_anything/zoom/core/auth.py |
Add verbose docstrings with examples |
from typing import Optional
from lxml import etree
from ..utils import mlt_xml
from .session import Session
# Registry of available transition types
TRANSITION_REGISTRY = {
"dissolve": {
"service": "luma",
"category": "video",
"description": "Cross-dissolve between two clips",
"p... | --- +++ @@ -1,3 +1,4 @@+"""Transition management: add, remove, configure transitions between clips."""
from typing import Optional
from lxml import etree
@@ -137,6 +138,7 @@
def list_available_transitions(category: Optional[str] = None) -> list[dict]:
+ """List all available transition types."""
result ... | https://raw.githubusercontent.com/HKUDS/CLI-Anything/HEAD/shotcut/agent-harness/cli_anything/shotcut/core/transitions.py |
Write Python docstrings for this snippet | import base64
import enum
import hashlib
import json
import logging
import os
import sys
import keyring
from buzz.settings.settings import APP_NAME
class Key(enum.Enum):
OPENAI_API_KEY = "OpenAI API key"
def _is_linux() -> bool:
return sys.platform.startswith("linux")
def _get_secrets_file_path() -> str... | --- +++ @@ -20,6 +20,7 @@
def _get_secrets_file_path() -> str:
+ """Get the path to the local encrypted secrets file."""
from platformdirs import user_data_dir
data_dir = user_data_dir(APP_NAME)
@@ -28,6 +29,12 @@
def _get_portal_secret() -> bytes | None:
+ """Get the application secret from X... | https://raw.githubusercontent.com/chidiwilliams/buzz/HEAD/buzz/store/keyring_store.py |
Document functions with clear intent | import datetime
import logging
import platform
import os
import sys
import wave
import time
import tempfile
import threading
import subprocess
from typing import Optional
from platformdirs import user_cache_dir
# Preload CUDA libraries before importing torch
from buzz import cuda_setup # noqa: F401
import torch
impo... | --- +++ @@ -336,6 +336,10 @@
@staticmethod
def get_device_sample_rate(device_id: Optional[int]) -> int:
+ """Returns the sample rate to be used for recording. It uses the default sample rate
+ provided by Whisper if the microphone supports it, or else it uses the device's default
+ sampl... | https://raw.githubusercontent.com/chidiwilliams/buzz/HEAD/buzz/transcriber/recording_transcriber.py |
Add docstrings with type hints explained | import platform
import os
import sys
import logging
import subprocess
import json
from typing import List
from buzz.assets import APP_BASE_DIR
from buzz.transcriber.transcriber import Segment, Task, FileTranscriptionTask
from buzz.transcriber.file_transcriber import app_env
IS_VULKAN_SUPPORTED = False
try:
import... | --- +++ @@ -35,6 +35,7 @@ class WhisperCpp:
@staticmethod
def transcribe(task: FileTranscriptionTask) -> List[Segment]:
+ """Transcribe audio using whisper-cli subprocess."""
cli_executable = "whisper-cli.exe" if sys.platform == "win32" else "whisper-cli"
whisper_cli_path = os.path.jo... | https://raw.githubusercontent.com/chidiwilliams/buzz/HEAD/buzz/transcriber/whisper_cpp.py |
Write reusable docstrings |
from typing import Any
from cli_anything.zoom.utils.zoom_backend import api_get, api_post, api_patch, api_delete
def create_meeting(
topic: str,
start_time: str | None = None,
duration: int = 60,
timezone: str = "UTC",
meeting_type: int = 2,
agenda: str = "",
password: str | None = None,
... | --- +++ @@ -1,3 +1,11 @@+"""Meeting management — CRUD operations via Zoom API.
+
+Covers:
+- Create / update / delete meetings
+- List meetings
+- Get meeting details
+- Meeting settings (recording, waiting room, etc.)
+"""
from typing import Any
from cli_anything.zoom.utils.zoom_backend import api_get, api_post, a... | https://raw.githubusercontent.com/HKUDS/CLI-Anything/HEAD/zoom/agent-harness/cli_anything/zoom/core/meetings.py |
Replace inline comments with docstrings | import os
import logging
from typing import Tuple, List, Optional
from uuid import UUID
from PyQt6 import QtGui
from PyQt6.QtCore import (
Qt,
QThread,
QModelIndex,
pyqtSignal
)
from PyQt6.QtGui import QIcon
from PyQt6.QtWidgets import (
QApplication,
QMainWindow,
QMessageBox,
QFileDia... | --- +++ @@ -504,6 +504,7 @@ self.settings.end_group()
def _init_update_checker(self):
+ """Initializes and runs the update checker."""
self.update_checker = UpdateChecker(settings=self.settings, parent=self)
self.update_checker.update_available.connect(self._on_update_available)
... | https://raw.githubusercontent.com/chidiwilliams/buzz/HEAD/buzz/widgets/main_window.py |
Add professional docstrings to my codebase | import datetime
import json
import logging
import multiprocessing
import re
import os
import sys
# Preload CUDA libraries before importing torch - required for subprocess contexts
from buzz import cuda_setup # noqa: F401
import torch
import platform
import subprocess
from platformdirs import user_cache_dir
from mult... | --- +++ @@ -38,6 +38,11 @@
def check_file_has_audio_stream(file_path: str) -> None:
+ """Check if a media file has at least one audio stream.
+
+ Raises:
+ ValueError: If the file has no audio streams.
+ """
try:
with av.open(file_path) as container:
if len(container.strea... | https://raw.githubusercontent.com/chidiwilliams/buzz/HEAD/buzz/transcriber/whisper_file_transcriber.py |
Create documentation for each function signature |
from typing import Optional
from lxml import etree
from ..utils import mlt_xml
from .session import Session
# Available blend modes for the cairo blend transition
BLEND_MODES = {
"normal": {"value": "normal", "description": "Normal compositing (default)"},
"add": {"value": "add", "description": "Additive bl... | --- +++ @@ -1,3 +1,4 @@+"""Compositing: blend modes, picture-in-picture, and layer compositing."""
from typing import Optional
from lxml import etree
@@ -30,11 +31,19 @@
def list_blend_modes() -> list[dict]:
+ """List all available blend modes."""
return [{"name": name, **info} for name, info in sorted(... | https://raw.githubusercontent.com/HKUDS/CLI-Anything/HEAD/shotcut/agent-harness/cli_anything/shotcut/core/compositing.py |
Can you add docstrings to this Python file? | import logging
from typing import Tuple, Optional
from PyQt6 import QtGui
from PyQt6.QtCore import QTime, QUrl, Qt, pyqtSignal
from PyQt6.QtMultimedia import QAudioOutput, QMediaPlayer, QMediaDevices
from PyQt6.QtWidgets import QWidget, QSlider, QPushButton, QLabel, QHBoxLayout, QVBoxLayout
from buzz.widgets.icon imp... | --- +++ @@ -173,6 +173,7 @@ self.media_player.play()
def set_range(self, range_ms: Tuple[int, int]):
+ """Set a loop range. Only jump to start if current position is outside the range."""
self.range_ms = range_ms
start_range_ms, end_range_ms = range_ms
@@ -182,9 +18... | https://raw.githubusercontent.com/chidiwilliams/buzz/HEAD/buzz/widgets/audio_player.py |
Document this code for team use | #!/usr/bin/env python3
import sys
import os
import json
import webbrowser
import click
from typing import Optional
# Add parent to path for imports
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
from cli_anything.zoom.core import auth as auth_mod
from cli_anything.zoom.core import me... | --- +++ @@ -1,4 +1,26 @@ #!/usr/bin/env python3
+"""Zoom CLI — Manage Zoom meetings, participants, and recordings from the command line.
+
+This CLI wraps the Zoom REST API v2 via OAuth2. It covers the full
+meeting lifecycle: authentication, meeting CRUD, participant management,
+recording retrieval, and reporting.
+
... | https://raw.githubusercontent.com/HKUDS/CLI-Anything/HEAD/zoom/agent-harness/cli_anything/zoom/zoom_cli.py |
Write reusable docstrings | import enum
import hashlib
import logging
import os
import time
import threading
import shutil
import subprocess
import sys
import ssl
import warnings
import platform
# Fix SSL certificate verification for bundled applications (macOS, Windows).
# This must be done before importing libraries that make HTTPS requests.
t... | --- +++ @@ -66,6 +66,7 @@ _original_create_symlink = file_download._create_symlink
def _windows_create_symlink(src: Path, dst: Path, new_blob: bool = False) -> None:
+ """Windows-compatible replacement that copies instead of symlinking."""
src = Path(src)
dst = Pa... | https://raw.githubusercontent.com/chidiwilliams/buzz/HEAD/buzz/model_loader.py |
Create docstrings for all classes and functions | from PyQt6.QtGui import QIcon, QPixmap, QPainter, QPalette
from PyQt6.QtCore import QSize
from PyQt6.QtSvg import QSvgRenderer
import os
from buzz.assets import APP_BASE_DIR
class PresentationIcon:
def __init__(self, parent, svg_path: str, color: str = None):
self.parent = parent
self.svg_path = sv... | --- +++ @@ -5,6 +5,7 @@ from buzz.assets import APP_BASE_DIR
class PresentationIcon:
+ "Icons for presentation window controls"
def __init__(self, parent, svg_path: str, color: str = None):
self.parent = parent
self.svg_path = svg_path
@@ -12,12 +13,14 @@
def get_default_color(self)... | https://raw.githubusercontent.com/chidiwilliams/buzz/HEAD/buzz/widgets/icon_presentation.py |
Help me document legacy Python code | import csv
import io
import os
import re
import enum
import time
import requests
import logging
import datetime
import sounddevice
from enum import auto
from typing import Optional, Tuple, Any
from PyQt6.QtCore import QThread, Qt, QThreadPool, QTimer, pyqtSignal
from PyQt6.QtGui import QTextCursor, QCloseEvent, QColor... | --- +++ @@ -242,6 +242,7 @@ self.copy_actions_bar.hide()
def create_presentation_options_bar(self) -> QWidget:
+ """Crete the presentation options bar widget"""
bar = QWidget(self)
layout = QHBoxLayout(bar)
@@ -317,6 +318,7 @@ return bar
def create_copy_actions_b... | https://raw.githubusercontent.com/chidiwilliams/buzz/HEAD/buzz/widgets/recording_transcriber_widget.py |
Help me add docstrings to my project | import os
import re
import logging
import queue
from typing import Optional, List, Tuple
from openai import OpenAI, max_retries
from PyQt6.QtCore import QObject, pyqtSignal
from buzz.locale import _
from buzz.settings.settings import Settings
from buzz.store.keyring_store import get_password, Key
from buzz.transcribe... | --- +++ @@ -57,6 +57,7 @@ )
def _translate_single(self, transcript: str, transcript_id: int) -> Tuple[str, int]:
+ """Translate a single transcript via the API. Returns (translation, transcript_id)."""
try:
completion = self.openai_client.chat.completions.create(
... | https://raw.githubusercontent.com/chidiwilliams/buzz/HEAD/buzz/translator.py |
Write Python docstrings for this snippet | import json
import logging
import platform
from datetime import datetime
from typing import Optional
from dataclasses import dataclass
from PyQt6.QtCore import QObject, pyqtSignal, QUrl
from PyQt6.QtNetwork import QNetworkAccessManager, QNetworkRequest, QNetworkReply
from buzz.__version__ import VERSION
from buzz.sett... | --- +++ @@ -40,6 +40,7 @@ self.network_manager.finished.connect(self._on_reply_finished)
def should_check_for_updates(self) -> bool:
+ """Check if we are on Windows/macOS and if 7 days passed"""
system = platform.system()
if system not in ("Windows", "Darwin"):
loggi... | https://raw.githubusercontent.com/chidiwilliams/buzz/HEAD/buzz/update_checker.py |
Fill in missing docstrings in my code | import enum
import logging
import os
from dataclasses import dataclass
from datetime import datetime, timedelta
from enum import auto
from typing import Optional, List
from uuid import UUID
from PyQt6 import QtGui
from PyQt6.QtCore import Qt
from PyQt6.QtCore import pyqtSignal, QModelIndex
from PyQt6.QtSql import QSql... | --- +++ @@ -324,21 +324,26 @@ self.settings.end_group()
def on_column_resized(self, logical_index: int, old_size: int, new_size: int):
+ """Handle column resize events"""
self.save_column_widths()
def on_column_moved(self, logical_index: int, old_visual_index: int, new_visual_index... | https://raw.githubusercontent.com/chidiwilliams/buzz/HEAD/buzz/widgets/transcription_tasks_table_widget.py |
Annotate my code with docstrings | import enum
import logging
from dataclasses import dataclass
from typing import Optional
from uuid import UUID
from PyQt6.QtCore import pyqtSignal, Qt, QModelIndex, QItemSelection, QEvent, QRegularExpression, QObject
from PyQt6.QtGui import QRegularExpressionValidator
from PyQt6.QtSql import QSqlTableModel, QSqlRecord... | --- +++ @@ -40,6 +40,7 @@
def parse_timestamp(timestamp_str: str) -> Optional[int]:
+ """Parse timestamp string (HH:MM:SS.mmm) to milliseconds"""
try:
# Handle formats like "00:01:23.456" or "1:23.456" or "23.456"
parts = timestamp_str.strip().split(':')
@@ -69,6 +70,7 @@
class TimeSta... | https://raw.githubusercontent.com/chidiwilliams/buzz/HEAD/buzz/widgets/transcription_viewer/transcription_segments_editor_widget.py |
Can you add docstrings to this Python file? | import os
import logging
import platform
from typing import Optional
from uuid import UUID
from PyQt6.QtCore import Qt, QThread, pyqtSignal, QTimer
from PyQt6.QtGui import QTextCursor
from PyQt6.QtMultimedia import QMediaPlayer
from PyQt6.QtSql import QSqlRecord
from PyQt6.QtWidgets import (
QWidget,
QVBoxLayo... | --- +++ @@ -403,6 +403,7 @@ self.current_media_player.media_player.play()
def restore_ui_state(self):
+ """Restore UI state from settings"""
# Restore playback controls visibility
if self.playback_controls_visible:
self.show_loop_controls()
@@ -412,6 +413,7 @@ ... | https://raw.githubusercontent.com/chidiwilliams/buzz/HEAD/buzz/widgets/transcription_viewer/transcription_viewer_widget.py |
Generate missing documentation strings |
from typing import Optional
from lxml import etree
from ..utils import mlt_xml
from .session import Session
# Registry of commonly used MLT filters with their parameters
FILTER_REGISTRY = {
# Video filters
"brightness": {
"service": "brightness",
"category": "video",
"description": "... | --- +++ @@ -1,3 +1,4 @@+"""Filter management: apply, remove, configure filters on clips and tracks."""
from typing import Optional
from lxml import etree
@@ -726,6 +727,11 @@
def list_available_filters(category: Optional[str] = None) -> list[dict]:
+ """List all available filters from the registry.
+
+ Ar... | https://raw.githubusercontent.com/HKUDS/CLI-Anything/HEAD/shotcut/agent-harness/cli_anything/shotcut/core/filters.py |
Add well-formatted docstrings | import logging
import os
import platform
import subprocess
import tempfile
from typing import Optional
from PyQt6.QtCore import Qt, QUrl
from PyQt6.QtWidgets import QApplication
from PyQt6.QtGui import QIcon
from PyQt6.QtNetwork import QNetworkAccessManager, QNetworkRequest, QNetworkReply
from PyQt6.QtWidgets import (... | --- +++ @@ -27,6 +27,7 @@ from buzz.widgets.icon import BUZZ_ICON_PATH
class UpdateDialog(QDialog):
+ """Dialog shows when an update is available"""
def __init__(
self,
update_info: UpdateInfo,
@@ -117,6 +118,7 @@ layout.addLayout(button_layout)
def _on_download_clicked(self)... | https://raw.githubusercontent.com/chidiwilliams/buzz/HEAD/buzz/widgets/update_dialog.py |
Expand my code with proper documentation strings |
import os
import subprocess
import shutil
from typing import Optional
from ..utils import mlt_xml
from .session import Session
# Export presets matching Shotcut's common presets
EXPORT_PRESETS = {
"default": {
"description": "H.264 High Profile, AAC (default quality)",
"vcodec": "libx264",
... | --- +++ @@ -1,3 +1,4 @@+"""Export/render operations: encode projects to video files."""
import os
import subprocess
@@ -144,6 +145,7 @@
def _build_brightness(props: dict) -> str:
+ """Convert MLT brightness filter to ffmpeg eq filter."""
level = props.get("level", "1.0")
# Check if it's a keyframed... | https://raw.githubusercontent.com/HKUDS/CLI-Anything/HEAD/shotcut/agent-harness/cli_anything/shotcut/core/export.py |
Write docstrings describing functionality | import logging
from typing import Tuple, Optional
from PyQt6.QtCore import Qt, QUrl, pyqtSignal, QTime
from PyQt6.QtMultimedia import QMediaPlayer, QAudioOutput, QMediaDevices
from PyQt6.QtMultimediaWidgets import QVideoWidget
from PyQt6.QtWidgets import QWidget, QVBoxLayout, QSlider, QPushButton, QHBoxLayout, QLabel, ... | --- +++ @@ -107,9 +107,11 @@ self.set_position(position)
def on_slider_pressed(self):
+ """Called when user starts dragging the slider"""
self.is_slider_dragging = True
def on_slider_released(self):
+ """Called when user releases the slider"""
self.is_slider_draggin... | https://raw.githubusercontent.com/chidiwilliams/buzz/HEAD/buzz/widgets/video_player.py |
Add docstrings with type hints explained | import glob
import subprocess
import sys
from pathlib import Path
from hatchling.builders.hooks.plugin.interface import BuildHookInterface
class CustomBuildHook(BuildHookInterface):
def initialize(self, version, build_data):
print("Running 'make buzz/whisper_cpp' to build whisper.cpp binaries...")
... | --- +++ @@ -1,3 +1,4 @@+"""Custom build hook for hatchling to build whisper.cpp binaries."""
import glob
import subprocess
import sys
@@ -7,8 +8,10 @@
class CustomBuildHook(BuildHookInterface):
+ """Build hook to compile whisper.cpp before building the package."""
def initialize(self, version, build_da... | https://raw.githubusercontent.com/chidiwilliams/buzz/HEAD/hatch_build.py |
Add docstrings to my Python code | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
from pathlib import Path
def read_news_items(news_file: Path, max_items: int = 10) -> list[str]:
with open(news_file, "r", encoding="utf-8") as f:
content = f.read()
# Split by lines that start with "- **["
lines = content.strip().split("\n")
ne... | --- +++ @@ -1,10 +1,28 @@ #!/usr/bin/env python3
# -*- coding: utf-8 -*-
+"""
+Script to automatically update NEWS section in README files.
+Reads the first 10 news items from docs/NEWS.md and updates README.md and
+README_zh.md.
+"""
from pathlib import Path
def read_news_items(news_file: Path, max_items: int... | https://raw.githubusercontent.com/agentscope-ai/agentscope/HEAD/.github/scripts/update_news.py |
Document my Python code with docstrings | import os
import sys
import logging
import platform
import numpy as np
# Preload CUDA libraries before importing torch
from buzz import cuda_setup # noqa: F401
import torch
import requests
from typing import Union
from transformers import AutoModelForSpeechSeq2Seq, AutoProcessor, pipeline, BitsAndBytesConfig
from tr... | --- +++ @@ -19,10 +19,12 @@
def is_intel_mac() -> bool:
+ """Check if running on Intel Mac (x86_64)."""
return sys.platform == 'darwin' and platform.machine() == 'x86_64'
def is_peft_model(model_id: str) -> bool:
+ """Check if model is a PEFT model based on model ID containing '-peft'."""
retur... | https://raw.githubusercontent.com/chidiwilliams/buzz/HEAD/buzz/transformers_whisper.py |
Add docstrings to improve code quality | # -*- coding: utf-8 -*-
from agentscope.agent import ReActAgent, AgentBase
from agentscope.formatter import DashScopeChatFormatter
from agentscope.memory import InMemoryMemory
from agentscope.message import Msg
from agentscope.model import DashScopeChatModel
import asyncio
import os
from agentscope.tool import Toolki... | --- +++ @@ -1,4 +1,34 @@ # -*- coding: utf-8 -*-
+"""
+.. _react-agent:
+
+Create ReAct Agent
+====================
+
+AgentScope provides out-of-the-box ReAct agent ``ReActAgent`` under ``agentscope.agent`` that can be used directly.
+
+It supports the following features at the same time:
+
+- ✨ Basic features
+ - ... | https://raw.githubusercontent.com/agentscope-ai/agentscope/HEAD/docs/tutorial/en/src/quickstart_agent.py |
Create simple docstrings for beginners | # -*- coding: utf-8 -*-
import asyncio
import os
import tempfile
from agentscope.embedding import DashScopeTextEmbedding, FileEmbeddingCache
async def example_dashscope_embedding() -> None:
texts = [
"What is the capital of France?",
"Paris is the capital city of France.",
]
# Initializ... | --- +++ @@ -1,4 +1,36 @@ # -*- coding: utf-8 -*-
+"""
+.. _embedding:
+
+Embedding
+=========================
+
+In AgentScope, the embedding module provides a unified interface for vector representation generation, which features:
+
+- Support **caching embeddings** to avoid redundant API calls
+- Support **multiple e... | https://raw.githubusercontent.com/agentscope-ai/agentscope/HEAD/docs/tutorial/en/src/task_embedding.py |
Improve my code by adding docstrings | #!/usr/bin/env python3
import sys
import os
import json
import click
from typing import Optional
# Add parent to path for imports
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
from cli_anything.obs_studio.core.session import Session
from cli_anything.obs_studio.core import project a... | --- +++ @@ -1,4 +1,18 @@ #!/usr/bin/env python3
+"""OBS Studio CLI -- A stateful command-line interface for OBS scene collection editing.
+
+This CLI provides full OBS Studio scene management capabilities using a JSON
+scene collection format. No OBS installation required for editing.
+
+Usage:
+ # One-shot commands... | https://raw.githubusercontent.com/HKUDS/CLI-Anything/HEAD/obs-studio/agent-harness/cli_anything/obs_studio/obs_studio_cli.py |
Add structured docstrings to improve clarity | # -*- coding: utf-8 -*-
from a2a.types import AgentCard, AgentCapabilities
from v2.nacos import ClientConfig
from agentscope.a2a import WellKnownAgentCardResolver, NacosAgentCardResolver
from agentscope.agent import A2AAgent, UserAgent
from agentscope.message import Msg, TextBlock
from agentscope.tool import ToolResp... | --- +++ @@ -1,4 +1,43 @@ # -*- coding: utf-8 -*-
+"""
+.. _a2a:
+
+A2A Agent
+============================
+
+A2A (Agent-to-Agent) is an open standard protocol for enabling interoperable communication between different AI agents.
+
+AgentScope provides support for the A2A protocol at two levels: obtaining Agent Card in... | https://raw.githubusercontent.com/agentscope-ai/agentscope/HEAD/docs/tutorial/en/src/task_a2a.py |
Document my Python code with docstrings | # coding: utf-8
# https://gist.github.com/simonw/664b4b0851c1899dc55e1fb655181037
import logging
import re
import sqlite3
from textwrap import dedent
def dumb_migrate_db(db, schema, allow_deletions=False):
with DBMigrator(db, schema, allow_deletions) as migrator:
migrator.migrate()
return bool(migra... | --- +++ @@ -1,6 +1,12 @@ # coding: utf-8
# https://gist.github.com/simonw/664b4b0851c1899dc55e1fb655181037
+"""Simple declarative schema migration for SQLite.
+See <https://david.rothlis.net/declarative-schema-migration-for-sqlite>.
+Author: William Manley <will@stb-tester.com>.
+Copyright © 2019-2022 Stb-tester.co... | https://raw.githubusercontent.com/chidiwilliams/buzz/HEAD/buzz/db/migrator.py |
Generate missing documentation strings | # -*- coding: utf-8 -*-
import asyncio
from typing import Any, Type
from agentscope.agent import ReActAgentBase, AgentBase
from agentscope.message import Msg
# %%
# Hook Signature
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
#
# AgentScope provides unified hook signatures for all pre- and post-hooks as follows:
#
# **Pre-Hook... | --- +++ @@ -1,4 +1,66 @@ # -*- coding: utf-8 -*-
+"""
+.. _hook:
+
+Agent Hooks
+===========================
+
+Hooks are extension points in AgentScope that allow developers to customize agent behaviors at specific execution points, providing a flexible way to modify or extend the agent's functionality without changin... | https://raw.githubusercontent.com/agentscope-ai/agentscope/HEAD/docs/tutorial/en/src/task_hook.py |
Help me add docstrings to my project | # -*- coding: utf-8 -*-
# %%
QA_BENCHMARK_DATASET = [
{
"id": "qa_task_1",
"question": "What are the health benefits of regular exercise?",
"reference_output": "Regular exercise improves cardiovascular health, strengthens muscles and bones, "
"helps maintain a healthy weight, and ca... | --- +++ @@ -1,4 +1,37 @@ # -*- coding: utf-8 -*-
+"""
+Evaluation with OpenJudge
+=========================
+
+This guide introduces how to use [OpenJudge](https://github.com/agentscope-ai/OpenJudge) graders as AgentScope metrics to evaluate your multi-agent applications.
+OpenJudge is a comprehensive evaluation system... | https://raw.githubusercontent.com/agentscope-ai/agentscope/HEAD/docs/tutorial/en/src/task_eval_openjudge.py |
Generate documentation strings for clarity | # -*- coding: utf-8 -*-
import os
import asyncio
from agentscope.message import Msg
from agentscope.memory import InMemoryMemory
from agentscope.agent import ReActAgent
from agentscope.formatter import DashScopeChatFormatter
from agentscope.model import DashScopeChatModel
from agentscope.tool import Toolkit
# Creat... | --- +++ @@ -1,4 +1,26 @@ # -*- coding: utf-8 -*-
+"""
+.. _long-term-memory:
+
+Long-Term Memory
+========================
+
+In AgentScope, we provide a basic class for long-term memory (``LongTermMemoryBase``) and an implementation based on the `mem0 <https://github.com/mem0ai/mem0>`_ library (``Mem0LongTermMemory``)... | https://raw.githubusercontent.com/agentscope-ai/agentscope/HEAD/docs/tutorial/en/src/task_long_term_memory.py |
Add docstrings to my Python code | # -*- coding: utf-8 -*-
from agentscope.token import HuggingFaceTokenCounter
from agentscope.formatter import DashScopeMultiAgentFormatter
from agentscope.message import Msg, ToolResultBlock, ToolUseBlock, TextBlock
import asyncio, json
input_msgs = [
# System prompt
Msg("system", "You're a helpful assistant... | --- +++ @@ -1,4 +1,153 @@ # -*- coding: utf-8 -*-
+"""
+.. _prompt:
+
+Prompt Formatter
+=========================
+
+The formatter module in AgentScope is responsible for
+
+- converting messages into the expected format for different LLM APIs,
+- (optional) truncating messages to fit within token limits,
+- (optional... | https://raw.githubusercontent.com/agentscope-ai/agentscope/HEAD/docs/tutorial/en/src/task_prompt.py |
Add detailed documentation for each class | # -*- coding: utf-8 -*-
import asyncio
import os
from agentscope.agent import ReActAgent
from agentscope.formatter import DashScopeChatFormatter
from agentscope.model import DashScopeChatModel
from agentscope.plan import PlanNotebook, Plan, SubTask
# %%
# PlanNotebook
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
#
# The `PlanN... | --- +++ @@ -1,4 +1,39 @@ # -*- coding: utf-8 -*-
+"""
+.. _plan:
+
+Plan
+=========================
+
+The Plan Module enables agents to formally break down complex tasks into manageable sub-tasks and execute them systematically. Key features include:
+
+- Support **manual plan specification**
+- Comprehensive plan man... | https://raw.githubusercontent.com/agentscope-ai/agentscope/HEAD/docs/tutorial/en/src/task_plan.py |
Create docstrings for all classes and functions | # -*- coding: utf-8 -*-
import asyncio
import json
import os
from agentscope.mcp import HttpStatefulClient, HttpStatelessClient
from agentscope.tool import Toolkit
# %%
# MCP Client
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
#
# In AgentScope, MCP clients are responsible for
#
# - connecting to the MCP server,
# - obtai... | --- +++ @@ -1,4 +1,33 @@ # -*- coding: utf-8 -*-
+"""
+.. _mcp:
+
+MCP
+=========================
+
+The tutorial covers the following features of AgentScope in support of the MCP (Model Context Protocol):
+
+- Support both **HTTP** (streamable HTTP and SSE) and **StdIO** MCP servers
+- Provide both **stateful** and **... | https://raw.githubusercontent.com/agentscope-ai/agentscope/HEAD/docs/tutorial/en/src/task_mcp.py |
Write beginner-friendly docstrings | # -*- coding: utf-8 -*-
import asyncio
import os
from agentscope.agent import RealtimeAgent
from agentscope.realtime import (
DashScopeRealtimeModel,
OpenAIRealtimeModel,
GeminiRealtimeModel,
)
# %%
# Creating Realtime Models
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
#
# AgentScope currently supports the following... | --- +++ @@ -1,4 +1,24 @@ # -*- coding: utf-8 -*-
+"""
+.. _realtime:
+
+Realtime Agent
+====================
+
+The **realtime** agent is designed to handle real-time interactions, such as
+voice conversations or live chat sessions.
+The realtime agent in AgentScope features:
+
+- Integration with OpenAI, DashScope, Ge... | https://raw.githubusercontent.com/agentscope-ai/agentscope/HEAD/docs/tutorial/en/src/task_realtime.py |
Expand my code with proper documentation strings | # -*- coding: utf-8 -*-
import asyncio
import os
from agentscope.agent import ReActAgent, UserAgent
from agentscope.formatter import DashScopeChatFormatter
from agentscope.message import Msg
from agentscope.model import DashScopeChatModel
from agentscope.tts import (
DashScopeRealtimeTTSModel,
DashScopeTTSMod... | --- +++ @@ -1,4 +1,71 @@ # -*- coding: utf-8 -*-
+"""
+.. _tts:
+
+TTS
+====================
+
+AgentScope provides a unified interface for Text-to-Speech (TTS) models across multiple API providers.
+This tutorial demonstrates how to use TTS models in AgentScope.
+
+AgentScope supports the following TTS APIs:
+
+.. lis... | https://raw.githubusercontent.com/agentscope-ai/agentscope/HEAD/docs/tutorial/en/src/task_tts.py |
Please document this code using docstrings | # -*- coding: utf-8 -*-
import asyncio
import os
from agentscope.agent import ReActAgent
from agentscope.formatter import DashScopeChatFormatter
from agentscope.memory import InMemoryMemory
from agentscope.message import Msg
from agentscope.model import DashScopeChatModel
from agentscope.tool import (
ToolRespons... | --- +++ @@ -1,4 +1,19 @@ # -*- coding: utf-8 -*-
+"""
+Handoffs
+========================================
+
+.. figure:: ../../_static/images/handoffs.png
+ :width: 80%
+ :align: center
+ :alt: Orchestrator-Workers Workflow
+
+ *Handoffs example*
+
+It's very simple to implement the Orchestrator-Workers workflo... | https://raw.githubusercontent.com/agentscope-ai/agentscope/HEAD/docs/tutorial/en/src/workflow_handoffs.py |
Document functions with clear intent | # -*- coding: utf-8 -*-
# %%
# 获取 Agent Card
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
#
# 首先,我们需要获得一个 Agent Card 来连接对应的智能体。Agent Card 中包含了智能体的名称,描述,能力以及连接方式等信息。
#
# 手动创建 Agent Card 对象
# --------------------------------
#
# 在已知 Agent Card 各项信息的情况下,可以直接从 `a2a.types.AgentCard` 手动创建 Agent Card 对象。
#
from a2a.types import AgentCa... | --- +++ @@ -1,4 +1,44 @@ # -*- coding: utf-8 -*-
+"""
+.. _a2a:
+
+A2A 智能体
+============================
+
+A2A(Agent-to-Agent)是一种开放标准协议,用于实现不同 AI 智能体之间的互操作通信。
+
+AgentScope 从获取 Agent Card 信息和连接远程智能体两个层面提供对 A2A 协议的支持,涉及到的相关 API 如下:
+
+.. list-table:: A2A 相关类
+ :header-rows: 1
+
+ * - 类
+ - 描述
+ * - ``A2AA... | https://raw.githubusercontent.com/agentscope-ai/agentscope/HEAD/docs/tutorial/zh_CN/src/task_a2a.py |
Add docstrings to clarify complex logic | # -*- coding: utf-8 -*-
import asyncio
import json
import os
from agentscope.agent import ReActAgent, UserAgent
from agentscope.memory import InMemoryMemory
from agentscope.formatter import (
DashScopeChatFormatter,
DashScopeMultiAgentFormatter,
)
from agentscope.model import DashScopeChatModel
from agentscope... | --- +++ @@ -1,4 +1,25 @@ # -*- coding: utf-8 -*-
+"""
+.. _conversation:
+
+Conversation
+======================
+
+Conversation is a design pattern that agents exchange and share information
+between each other, most commonly in game playing, chatbot, and multi-agent
+discussion scenarios.
+
+In AgentScope, the conver... | https://raw.githubusercontent.com/agentscope-ai/agentscope/HEAD/docs/tutorial/en/src/workflow_conversation.py |
Generate consistent documentation across files | # -*- coding: utf-8 -*-
import asyncio
import os
from pydantic import Field, BaseModel
from agentscope.agent import ReActAgent
from agentscope.formatter import (
DashScopeMultiAgentFormatter,
DashScopeChatFormatter,
)
from agentscope.message import Msg
from agentscope.model import DashScopeChatModel
from agen... | --- +++ @@ -1,4 +1,17 @@ # -*- coding: utf-8 -*-
+"""
+.. _multiagent-debate:
+
+Multi-Agent Debate
+========================
+
+Debate workflow simulates a multi-turn discussion between different agents, mostly several solvers and an aggregator.
+Typically, the solvers generate and exchange their answers, while the ag... | https://raw.githubusercontent.com/agentscope-ai/agentscope/HEAD/docs/tutorial/en/src/workflow_multiagent_debate.py |
Generate docstrings for script automation | # -*- coding: utf-8 -*-
import os
import asyncio
from agentscope.message import Msg
from agentscope.memory import InMemoryMemory, Mem0LongTermMemory
from agentscope.agent import ReActAgent
from agentscope.embedding import DashScopeTextEmbedding
from agentscope.formatter import DashScopeChatFormatter
from agentscope.m... | --- +++ @@ -1,4 +1,26 @@ # -*- coding: utf-8 -*-
+"""
+.. _long-term-memory:
+
+长期记忆
+========================
+
+AgentScope 为长期记忆提供了一个基类 ``LongTermMemoryBase`` 和一个基于 `mem0 <https://github.com/mem0ai/mem0>`_ 的具体实现 ``Mem0LongTermMemory``。
+结合 :ref:`agent` 章节中 ``ReActAgent`` 类的设计,我们提供了两种长期记忆模式:
+
+- ``agent_control``:智能体... | https://raw.githubusercontent.com/agentscope-ai/agentscope/HEAD/docs/tutorial/zh_CN/src/task_long_term_memory.py |
Fully document this Python code with docstrings | # -*- coding: utf-8 -*-
import asyncio
import json
import os
from matplotlib import pyplot as plt
import agentscope
from agentscope.agent import ReActAgent
from agentscope.embedding import (
DashScopeTextEmbedding,
DashScopeMultiModalEmbedding,
)
from agentscope.formatter import DashScopeChatFormatter
from ag... | --- +++ @@ -1,4 +1,43 @@ # -*- coding: utf-8 -*-
+"""
+.. _rag:
+
+RAG
+==========================
+
+AgentScope 提供了内置的 RAG(Retrieval-Augmented Generation) 实现。本节将详细介绍
+
+- 如何使用 AgentScope 中的 RAG 模块,
+- 如何实现 **多模态** RAG,
+- 如何在 ``ReActAgent`` 中以两种不同的方式集成 RAG 模块:
+ - 智能体自主控制(Agentic manner)
+ - 通用方式(Generic manner)... | https://raw.githubusercontent.com/agentscope-ai/agentscope/HEAD/docs/tutorial/zh_CN/src/task_rag.py |
Generate docstrings with parameter types | # -*- coding: utf-8 -*-
import asyncio
from typing import AsyncGenerator, Callable
from agentscope.message import TextBlock, ToolUseBlock
from agentscope.tool import ToolResponse, Toolkit
# %%
# 工具执行中间件
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
#
# ``Toolkit`` 类通过 ``register_middleware`` 方法支持工具执行的中间件。
# 每个中间件可以拦截工具调用并修改输入或... | --- +++ @@ -1,4 +1,24 @@ # -*- coding: utf-8 -*-
+"""
+.. _middleware:
+
+中间件
+===========================
+
+AgentScope 提供了灵活的中间件系统,允许开发者拦截和修改各种操作的执行。
+目前,中间件支持已在 ``Toolkit`` 类中实现,用于**工具执行**。
+
+中间件系统遵循**洋葱模型**,每个中间件包裹在前一个中间件之外,形成层次结构。
+这使得开发者可以:
+
+- 在操作前进行**预处理**
+- 在执行过程中**拦截和修改**响应
+- 在操作完成后进行**后处理**
+- 根据条件**跳过**... | https://raw.githubusercontent.com/agentscope-ai/agentscope/HEAD/docs/tutorial/zh_CN/src/task_middleware.py |
Add docstrings for utility scripts | # -*- coding: utf-8 -*-
import asyncio
import os
from agentscope.agent import ReActAgent
from agentscope.formatter import DashScopeChatFormatter
from agentscope.memory import InMemoryMemory
from agentscope.message import Msg
from agentscope.model import DashScopeChatModel
from agentscope.tool import (
ToolRespons... | --- +++ @@ -1,4 +1,21 @@ # -*- coding: utf-8 -*-
+"""
+.. _handoffs:
+
+Handoffs
+========================================
+
+Handoffs 是由 OpenAI 提出的工作流模式,通过调用子智能体的方式来完成目标任务。
+在 AgentScope 中通过工具调用的方式实现 handoffs 非常简单。首先,我们创建一个函数来允许协调者动态创建子智能体。
+
+.. figure:: ../../_static/images/handoffs.png
+ :width: 80%
+ :align: c... | https://raw.githubusercontent.com/agentscope-ai/agentscope/HEAD/docs/tutorial/zh_CN/src/workflow_handoffs.py |
Write docstrings including parameters and return values | import logging
from typing import Optional
from PyQt6.QtCore import Qt
from PyQt6.QtGui import QTextCursor
from PyQt6.QtWidgets import QWidget, QVBoxLayout, QTextBrowser
from platformdirs import user_cache_dir
from buzz.locale import _
from buzz.settings.settings import Settings
import os
class PresentationWindow(QW... | --- +++ @@ -11,6 +11,7 @@ import os
class PresentationWindow(QWidget):
+ """Window for displaying live transcripts in presentation mode"""
def __init__(self, parent: Optional[QWidget] = None):
super().__init__(parent)
@@ -46,6 +47,7 @@ self.load_settings()
def load_settings(self):
+... | https://raw.githubusercontent.com/chidiwilliams/buzz/HEAD/buzz/widgets/presentation_window.py |
Add docstrings to improve collaboration | # -*- coding: utf-8 -*-
from typing import Dict, Optional
from agentscope.agent import ReActAgent
from agentscope.formatter import OpenAIChatFormatter
from agentscope.message import Msg
from agentscope.model import ChatModelBase
from agentscope.tuner import WorkflowOutput
async def example_workflow_function(
tas... | --- +++ @@ -1,4 +1,79 @@ # -*- coding: utf-8 -*-
+"""
+.. _tuner:
+
+Tuner
+=================
+
+AgentScope 提供了 ``tuner`` 模块,用于通过强化学习(RL)训练智能体应用。
+本教程将带你系统了解如何利用 ``tuner`` 提升智能体在特定任务上的表现,包括:
+
+- 介绍 ``tuner`` 的核心组件
+- 演示调优流程所需的关键代码实现
+- 展示调优流程的配置与运行方法
+
+主要组件
+~~~~~~~~~~~~~~~~~~~
+``tuner`` 模块为智能体训练工作流引入了三大核心组件:
+
+- *... | https://raw.githubusercontent.com/agentscope-ai/agentscope/HEAD/docs/tutorial/zh_CN/src/task_tuner.py |
Generate documentation strings for clarity | # -*- coding: utf-8 -*-
# %%
QA_BENCHMARK_DATASET = [
{
"id": "qa_task_1",
"question": "What are the health benefits of regular exercise?",
"reference_output": "Regular exercise improves cardiovascular health, strengthens muscles and bones, "
"helps maintain a healthy weight, and ca... | --- +++ @@ -1,4 +1,35 @@ # -*- coding: utf-8 -*-
+"""
+OpenJudge 评估器
+=======================
+
+[OpenJudge](https://github.com/agentscope-ai/OpenJudge) 是一个专为评估LLM/Agent应用质量而设计的评估框架。通过将 OpenJudge 集成到 AgentScope 中,您可以将 AgentScope 的原生评估能力从基础的执行检查扩展到深度的语义质量分析。
+
+本指南中我们将介绍如何使用 OpenJudge 的评估器(Grader)作为 AgentScope 的评估指标(Met... | https://raw.githubusercontent.com/agentscope-ai/agentscope/HEAD/docs/tutorial/zh_CN/src/task_eval_openjudge.py |
Write docstrings describing functionality | # -*- coding: utf-8 -*-
import asyncio
import json
import fakeredis
from sqlalchemy.ext.asyncio import create_async_engine
from agentscope.memory import (
InMemoryMemory,
AsyncSQLAlchemyMemory,
RedisMemory,
)
from agentscope.message import Msg
# %%
# 内存记忆
# ~~~~~~~~~~~~~~~~~~~~~~~~
#
# 内存记忆提供了一种在内存中存储消息... | --- +++ @@ -1,4 +1,73 @@ # -*- coding: utf-8 -*-
+"""
+.. _memory:
+
+记忆
+========================
+
+AgentScope 中的记忆模块负责:
+
+- 存储消息对象(``Msg``)
+- 利用标记(mark)管理消息
+
+**标记** 是与记忆中每条消息关联的字符串标签,可用于根据消息的上下文或目的对消息进行分类、过滤和检索。
+可用于实现进阶的记忆管理功能,例如在 `ReActAgent` 类中,使用``"hint"``标签标记一次性的提示消息,
+以便在使用完成后将其从记忆中删除。
+
+.. note:: AgentSc... | https://raw.githubusercontent.com/agentscope-ai/agentscope/HEAD/docs/tutorial/zh_CN/src/task_memory.py |
Add docstrings for production code | from typing import Optional
from PyQt6.QtCore import pyqtSignal
from PyQt6.QtWidgets import QWidget, QSizePolicy
from buzz.locale import _
from buzz.widgets.line_edit import LineEdit
class MMSLanguageLineEdit(LineEdit):
languageChanged = pyqtSignal(str)
def __init__(
self,
default_language... | --- +++ @@ -8,6 +8,11 @@
class MMSLanguageLineEdit(LineEdit):
+ """Text input for MMS language codes (ISO 639-3).
+
+ MMS models support 1000+ languages using ISO 639-3 codes (3 letters).
+ Examples: eng (English), fra (French), deu (German), spa (Spanish)
+ """
languageChanged = pyqtSignal(str)
... | https://raw.githubusercontent.com/chidiwilliams/buzz/HEAD/buzz/widgets/transcriber/mms_language_line_edit.py |
Fill in missing docstrings in my code | import os
import logging
import platform
from typing import Optional, List
from PyQt6.QtCore import pyqtSignal, QLocale
from PyQt6.QtGui import QIcon
from PyQt6.QtWidgets import QGroupBox, QWidget, QFormLayout, QComboBox, QLabel, QHBoxLayout
from buzz.locale import _
from buzz.settings.settings import Settings
from b... | --- +++ @@ -146,6 +146,7 @@ self.transcription_options_changed.emit(self.transcription_options)
def on_mms_language_changed(self, language: str):
+ """Handle MMS language code changes."""
if language == "":
language = "eng" # Default to English for MMS
@@ -281,6 +282,7 @@ ... | https://raw.githubusercontent.com/chidiwilliams/buzz/HEAD/buzz/widgets/transcriber/transcription_options_group_box.py |
Write docstrings for algorithm functions | # -*- coding: utf-8 -*-
from typing import Dict, Optional
from agentscope.agent import ReActAgent
from agentscope.formatter import OpenAIChatFormatter
from agentscope.message import Msg
from agentscope.model import ChatModelBase
from agentscope.tuner import WorkflowOutput
async def example_workflow_function(
tas... | --- +++ @@ -1,4 +1,79 @@ # -*- coding: utf-8 -*-
+"""
+.. _tuner:
+
+Tuner
+=================
+
+AgentScope provides the ``tuner`` module for training agent applications using reinforcement learning (RL).
+This tutorial will guide you through how to leverage the ``tuner`` module to improve agent performance on specific... | https://raw.githubusercontent.com/agentscope-ai/agentscope/HEAD/docs/tutorial/en/src/task_tuner.py |
Write docstrings for backend logic | import re
import os
import logging
import ssl
import time
import random
from typing import Optional
# Fix SSL certificate verification for bundled applications (macOS, Windows)
# This must be done before importing libraries that download from Hugging Face
try:
import certifi
os.environ.setdefault('REQUESTS_CA_... | --- +++ @@ -56,6 +56,36 @@ exception_types=(AssertionError,),
**process_func_kwargs
):
+ """
+ Process items in batches with automatic fallback to smaller batches on errors.
+
+ This is a generic batch processing function that can be used with any processing
+ function that has chunk size limi... | https://raw.githubusercontent.com/chidiwilliams/buzz/HEAD/buzz/widgets/transcription_viewer/speaker_identification_widget.py |
Create documentation for each function signature | # -*- coding: utf-8 -*-
import asyncio
import json
import os
from typing import Literal
from pydantic import BaseModel, Field
from agentscope.agent import ReActAgent
from agentscope.formatter import DashScopeChatFormatter
from agentscope.memory import InMemoryMemory
from agentscope.message import Msg
from agentscope.... | --- +++ @@ -1,4 +1,22 @@ # -*- coding: utf-8 -*-
+"""
+.. _routing:
+
+Routing
+==========================
+在 AgentScope 中有两种实现 Routing 的方法,都简单易实现:
+
+- 使用结构化输出的显式 routing
+- 使用工具调用的隐式 routing
+
+.. tip:: 考虑到智能体 routing 没有统一的标准/定义,我们遵循 `Building effective agents <https://www.anthropic.com/engineering/building-effective... | https://raw.githubusercontent.com/agentscope-ai/agentscope/HEAD/docs/tutorial/zh_CN/src/workflow_routing.py |
Document helper functions with docstrings | #!/usr/bin/env python
import getopt
import sys
import polib
def usage(ecode, msg=""):
print(__doc__, file=sys.stderr)
if msg:
print(msg, file=sys.stderr)
sys.exit(ecode)
def make(filename, outfile):
po = polib.pofile(filename)
po.save_as_mofile(outfile)
def main():
try:
opt... | --- +++ @@ -1,10 +1,32 @@ #!/usr/bin/env python
+"""
+Generate binary message catalog from textual translation description.
+
+This program converts a textual Uniforum-style message catalog (.po file) into
+a binary GNU catalog (.mo file). This is essentially the same function as the
+GNU msgfmt program, however, it i... | https://raw.githubusercontent.com/chidiwilliams/buzz/HEAD/msgfmt.py |
Generate docstrings for each module | # -*- coding: utf-8 -*-
import asyncio
import json
import os
from agentscope.agent import ReActAgent
from agentscope.formatter import DashScopeChatFormatter
from agentscope.memory import InMemoryMemory
from agentscope.message import Msg
from agentscope.model import DashScopeChatModel
from agentscope.module import Stat... | --- +++ @@ -1,4 +1,18 @@ # -*- coding: utf-8 -*-
+"""
+.. _state:
+
+State/Session Management
+=================================
+
+In AgentScope, the **"state"** refers to the agent status in the running application, including its current system prompt, memory, context, equipped tools, and other information that **cha... | https://raw.githubusercontent.com/agentscope-ai/agentscope/HEAD/docs/tutorial/en/src/task_state.py |
Create docstrings for all classes and functions | # -*- coding: utf-8 -*-
import asyncio
from typing import AsyncGenerator, Callable
from agentscope.message import TextBlock, ToolUseBlock
from agentscope.tool import ToolResponse, Toolkit
# %%
# Tool Execution Middleware
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
#
# The ``Toolkit`` class supports middleware for tool execut... | --- +++ @@ -1,4 +1,24 @@ # -*- coding: utf-8 -*-
+"""
+.. _middleware:
+
+Middleware
+===========================
+
+AgentScope provides a flexible middleware system that allows developers to intercept and modify the execution of various operations.
+Currently, middleware support is available for **tool execution** in ... | https://raw.githubusercontent.com/agentscope-ai/agentscope/HEAD/docs/tutorial/en/src/task_middleware.py |
Add missing documentation to my Python functions | # -*- coding: utf-8 -*-
import asyncio
import json
import os
from agentscope.message import TextBlock, ToolUseBlock, ThinkingBlock, Msg
from agentscope.model import ChatResponse, DashScopeChatModel
response = ChatResponse(
content=[
ThinkingBlock(
type="thinking",
thinking="I shoul... | --- +++ @@ -1,4 +1,82 @@ # -*- coding: utf-8 -*-
+"""
+.. _model:
+
+Model
+====================
+
+In this tutorial, we introduce the model APIs integrated in AgentScope, how to use them and how to integrate new model APIs.
+The supported model APIs and providers include:
+
+.. list-table::
+ :header-rows: 1
+
+ ... | https://raw.githubusercontent.com/agentscope-ai/agentscope/HEAD/docs/tutorial/en/src/task_model.py |
Add docstrings following best practices | # -*- coding: utf-8 -*-
TOY_BENCHMARK = [
{
"id": "math_problem_1",
"question": "What is 2 + 2?",
"ground_truth": 4.0,
"tags": {
"difficulty": "easy",
"category": "math",
},
},
{
"id": "math_problem_2",
"question": "What is 123... | --- +++ @@ -1,4 +1,55 @@ # -*- coding: utf-8 -*-
+"""
+.. _eval:
+
+Evaluation
+=========================
+
+AgentScope provides a built-in evaluation framework for assessing agent performance across different tasks and benchmarks, featuring:
+
+- `Ray <https://github.com/ray-project/ray>`_-based parallel and distribut... | https://raw.githubusercontent.com/agentscope-ai/agentscope/HEAD/docs/tutorial/en/src/task_eval.py |
Can you add docstrings to this Python file? | # -*- coding: utf-8 -*-
import asyncio
import inspect
import json
from typing import Any, AsyncGenerator
from pydantic import BaseModel, Field
import agentscope
from agentscope.message import TextBlock, ToolUseBlock
from agentscope.tool import ToolResponse, Toolkit, execute_python_code
# %%
# Tool Function
# ~~~~~~... | --- +++ @@ -1,4 +1,23 @@ # -*- coding: utf-8 -*-
+"""
+.. _tool:
+
+Tool
+=========================
+
+To ensure accurate and reliable tool parsing, AgentScope fully embraces the use of tools API with the following features:
+
+- Support **automatic** tool parsing from Python functions with their docstrings
+- Support ... | https://raw.githubusercontent.com/agentscope-ai/agentscope/HEAD/docs/tutorial/en/src/task_tool.py |
Document this script properly | # -*- coding: utf-8 -*-
import os, asyncio
from agentscope.formatter import DashScopeMultiAgentFormatter
from agentscope.message import Msg
from agentscope.model import DashScopeChatModel
from agentscope.agent import ReActAgent
from agentscope.pipeline import MsgHub, stream_printing_messages
# %%
# Broadcasting wit... | --- +++ @@ -1,4 +1,19 @@ # -*- coding: utf-8 -*-
+"""
+.. _pipeline:
+
+Pipeline
+========================
+
+For multi-agent orchestration, AgentScope provides the ``agentscope.pipeline`` module
+as syntax sugar for chaining agents together, including
+
+- **MsgHub**: a message hub for broadcasting messages among mult... | https://raw.githubusercontent.com/agentscope-ai/agentscope/HEAD/docs/tutorial/en/src/task_pipeline.py |
Add docstrings following best practices | # -*- coding: utf-8 -*-
import asyncio
import os
from agentscope.agent import ReActAgent
from agentscope.formatter import DashScopeChatFormatter
from agentscope.model import DashScopeChatModel
from agentscope.plan import PlanNotebook, Plan, SubTask
# %%
# PlanNotebook
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
#
# ``PlanNote... | --- +++ @@ -1,4 +1,38 @@ # -*- coding: utf-8 -*-
+"""
+.. _plan:
+
+计划
+=========================
+
+AgentScope 中的计划(Plan)模块使智能体能够正式地将复杂任务分解为可管理的子任务并系统地执行它们。主要功能包括:
+
+- 支持 **手动计划规范**
+- 全面的计划管理功能:
+ - **创建、修改、放弃和恢复** 计划
+ - 在多个计划之间 **切换**
+ - 通过临时暂停计划来处理用户查询或紧急任务,**优雅地处理中断**
+- 计划执行的 **实时可视化和监控**
+
+.. note:: 当前... | https://raw.githubusercontent.com/agentscope-ai/agentscope/HEAD/docs/tutorial/zh_CN/src/task_plan.py |
Turn comments into proper docstrings | # -*- coding: utf-8 -*-
import asyncio
import json
import os
from typing import Literal
from pydantic import BaseModel, Field
from agentscope.agent import ReActAgent
from agentscope.formatter import DashScopeChatFormatter
from agentscope.memory import InMemoryMemory
from agentscope.message import Msg
from agentscope.... | --- +++ @@ -1,4 +1,22 @@ # -*- coding: utf-8 -*-
+"""
+.. _routing:
+
+Routing
+==========================
+There are two ways to implement routing in AgentScope, both simple and easy to implement:
+
+- Routing by structured output
+- Routing by tool calls
+
+.. tip:: Considering there is no unified standard/definition... | https://raw.githubusercontent.com/agentscope-ai/agentscope/HEAD/docs/tutorial/en/src/workflow_routing.py |
Add docstrings to my Python code | # -*- coding: utf-8 -*-
import asyncio
import json
import os
from matplotlib import pyplot as plt
import agentscope
from agentscope.agent import ReActAgent
from agentscope.embedding import (
DashScopeTextEmbedding,
DashScopeMultiModalEmbedding,
)
from agentscope.formatter import DashScopeChatFormatter
from ag... | --- +++ @@ -1,4 +1,45 @@ # -*- coding: utf-8 -*-
+"""
+.. _rag:
+
+RAG
+===========================
+
+AgentScope provides built-in support for Retrieval-Augmented Generation (RAG)
+tasks. This tutorial demonstrates
+
+- how to use the RAG module in AgentScope,
+- how to use **multimodal** RAG,
+- how to integrate the ... | https://raw.githubusercontent.com/agentscope-ai/agentscope/HEAD/docs/tutorial/en/src/task_rag.py |
Write Python docstrings for this snippet | # -*- coding: utf-8 -*-
import asyncio
import inspect
import json
from typing import Any, AsyncGenerator
from pydantic import BaseModel, Field
import agentscope
from agentscope.message import TextBlock, ToolUseBlock
from agentscope.tool import ToolResponse, Toolkit, execute_python_code
# %%
# 工具函数
# ~~~~~~~~~~~~~~~... | --- +++ @@ -1,4 +1,23 @@ # -*- coding: utf-8 -*-
+"""
+.. _tool:
+
+工具
+=========================
+
+为了确保准确可靠的工具解析,AgentScope 全面支持工具 API 的使用,具有以下特性:
+
+- 支持从文档字符串 **自动** 解析工具函数
+- 支持 **同步和异步** 工具函数
+- 支持 **流式** 工具响应(同步或异步生成器)
+- 支持对工具 JSON Schema 的 **动态扩展**
+- 支持用户实时 **中断** 工具的执行
+- 支持智能体的 **自主工具管理**
+
+所有上述功能都由 AgentS... | https://raw.githubusercontent.com/agentscope-ai/agentscope/HEAD/docs/tutorial/zh_CN/src/task_tool.py |
Help me document legacy Python code | # -*- coding: utf-8 -*-
from contextvars import ContextVar
class _ConfigCls:
def __init__(
self,
run_id: ContextVar[str],
project: ContextVar[str],
name: ContextVar[str],
created_at: ContextVar[str],
trace_enabled: ContextVar[bool],
) -> None:
# Copy th... | --- +++ @@ -1,8 +1,10 @@ # -*- coding: utf-8 -*-
+"""The run instance configuration in agentscope."""
from contextvars import ContextVar
class _ConfigCls:
+ """The run instance configuration in agentscope."""
def __init__(
self,
@@ -12,6 +14,7 @@ created_at: ContextVar[str],
tr... | https://raw.githubusercontent.com/agentscope-ai/agentscope/HEAD/src/agentscope/_run_config.py |
Please document this code using docstrings | # -*- coding: utf-8 -*-
import json
from pathlib import Path
from typing import TYPE_CHECKING
from ._base import AgentCardResolverBase
if TYPE_CHECKING:
from a2a.types import AgentCard
else:
AgentCard = "a2a.types.AgentCard"
class FileAgentCardResolver(AgentCardResolverBase):
def __init__(
self... | --- +++ @@ -1,4 +1,5 @@ # -*- coding: utf-8 -*-
+"""The JSON file based A2A agent card resolver."""
import json
from pathlib import Path
from typing import TYPE_CHECKING
@@ -12,14 +13,55 @@
class FileAgentCardResolver(AgentCardResolverBase):
+ """Agent card resolver that loads AgentCard from a JSON file.
+
+ ... | https://raw.githubusercontent.com/agentscope-ai/agentscope/HEAD/src/agentscope/a2a/_file_resolver.py |
Generate descriptive docstrings automatically | # -*- coding: utf-8 -*-
# flake8: noqa: E402
# pylint: disable=wrong-import-position
import os
import warnings
from contextvars import ContextVar
from datetime import datetime
import requests
import shortuuid
from ._run_config import _ConfigCls
def _generate_random_suffix(length: int) -> str:
return shortuuid.u... | --- +++ @@ -1,6 +1,7 @@ # -*- coding: utf-8 -*-
# flake8: noqa: E402
# pylint: disable=wrong-import-position
+"""The agentscope serialization module"""
import os
import warnings
from contextvars import ContextVar
@@ -13,6 +14,7 @@
def _generate_random_suffix(length: int) -> str:
+ """Generate a random suffi... | https://raw.githubusercontent.com/agentscope-ai/agentscope/HEAD/src/agentscope/__init__.py |
Please document this code using docstrings | # -*- coding: utf-8 -*-
from abc import abstractmethod
from typing import Any, TYPE_CHECKING
if TYPE_CHECKING:
from a2a.types import AgentCard
else:
AgentCard = "a2a.types.AgentCard"
class AgentCardResolverBase:
@abstractmethod
async def get_agent_card(self, *args: Any, **kwargs: Any) -> AgentCard: | --- +++ @@ -1,4 +1,5 @@ # -*- coding: utf-8 -*-
+"""The A2A agent card resolver base class."""
from abc import abstractmethod
from typing import Any, TYPE_CHECKING
@@ -9,6 +10,16 @@
class AgentCardResolverBase:
+ """Base class for A2A agent card resolvers, responsible for fetching
+ agent cards from vario... | https://raw.githubusercontent.com/agentscope-ai/agentscope/HEAD/src/agentscope/a2a/_base.py |
Help me add docstrings to my project | # -*- coding: utf-8 -*-
import json
import os
from typing import Generator
import json5
import requests
from tqdm import tqdm
from ._ace_metric import ACEAccuracy, ACEProcessAccuracy
from ._ace_tools_zh import ACEPhone
from .._benchmark_base import BenchmarkBase
from .._task import Task
class ACEBenchmark(Benchmark... | --- +++ @@ -1,4 +1,7 @@ # -*- coding: utf-8 -*-
+"""The ACE benchmark class in agentscope. The code is implemented with
+reference to the `ACEBench <https://github.com/ACEBench/ACEBench>`_
+under the MIT license."""
import json
import os
from typing import Generator
@@ -14,6 +17,7 @@
class ACEBenchmark(Benchmark... | https://raw.githubusercontent.com/agentscope-ai/agentscope/HEAD/src/agentscope/evaluate/_ace_benchmark/_ace_benchmark.py |
Add inline docstrings for readability | # -*- coding: utf-8 -*-
from abc import abstractmethod
from typing import List, Any
from ..types import (
JSONSerializableObject,
Embedding,
)
class EmbeddingCacheBase:
@abstractmethod
async def store(
self,
embeddings: List[Embedding],
identifier: JSONSerializableObject,
... | --- +++ @@ -1,4 +1,5 @@ # -*- coding: utf-8 -*-
+"""The embedding cache base class."""
from abc import abstractmethod
from typing import List, Any
@@ -9,6 +10,8 @@
class EmbeddingCacheBase:
+ """Base class for embedding caches, which is responsible for storing and
+ retrieving embeddings."""
@abstr... | https://raw.githubusercontent.com/agentscope-ai/agentscope/HEAD/src/agentscope/embedding/_cache_base.py |
Generate consistent docstrings | # -*- coding: utf-8 -*-
from typing import TYPE_CHECKING
from ._base import AgentCardResolverBase
from .._logging import logger
if TYPE_CHECKING:
from a2a.types import AgentCard
from v2.nacos.common.client_config import ClientConfig
else:
AgentCard = "a2a.types.AgentCard"
ClientConfig = "v2.nacos.com... | --- +++ @@ -1,4 +1,5 @@ # -*- coding: utf-8 -*-
+"""The Nacos-based A2A Agent Card resolver."""
from typing import TYPE_CHECKING
@@ -14,6 +15,12 @@
class NacosAgentCardResolver(AgentCardResolverBase):
+ """Nacos-based A2A Agent Card resolver.
+
+ Nacos is a dynamic service discovery, configuration and se... | https://raw.githubusercontent.com/agentscope-ai/agentscope/HEAD/src/agentscope/a2a/_nacos_resolver.py |
Write beginner-friendly docstrings | # -*- coding: utf-8 -*-
import asyncio
import base64
import functools
import inspect
import json
import os
import tempfile
import types
import typing
import uuid
from datetime import datetime
from typing import Any, Callable, Type, Dict
import numpy as np
import requests
from docstring_parser import parse
from json_re... | --- +++ @@ -1,4 +1,5 @@ # -*- coding: utf-8 -*-
+"""The common utilities for agentscope library."""
import asyncio
import base64
import functools
@@ -30,6 +31,23 @@ def _json_loads_with_repair(
json_str: str,
) -> dict:
+ """The given json_str maybe incomplete, e.g. '{"key', so we need to
+ repair and lo... | https://raw.githubusercontent.com/agentscope-ai/agentscope/HEAD/src/agentscope/_utils/_common.py |
Generate documentation strings for clarity | # -*- coding: utf-8 -*-
from __future__ import annotations
from typing import TYPE_CHECKING, Any, Type
import httpx
from pydantic import BaseModel
from ._agent_base import AgentBase
from ..message import Msg
from ..formatter import A2AChatFormatter
if TYPE_CHECKING:
from a2a.types import AgentCard
from a2a.c... | --- +++ @@ -1,4 +1,10 @@ # -*- coding: utf-8 -*-
+"""A2A agent implementation for AgentScope.
+
+This module provides the A2A (Agent-to-Agent) protocol implementation,
+enabling AgentScope agents to communicate with remote agents using the
+A2A standard protocol.
+"""
from __future__ import annotations
from typing im... | https://raw.githubusercontent.com/agentscope-ai/agentscope/HEAD/src/agentscope/agent/_a2a_agent.py |
Add docstrings following best practices | # -*- coding: utf-8 -*-
from typing import Any
from ._embedding_response import EmbeddingResponse
class EmbeddingModelBase:
model_name: str
"""The embedding model name"""
supported_modalities: list[str]
"""The supported data modalities, e.g. "text", "image", "video"."""
dimensions: int
"""... | --- +++ @@ -1,10 +1,12 @@ # -*- coding: utf-8 -*-
+"""The embedding model base class."""
from typing import Any
from ._embedding_response import EmbeddingResponse
class EmbeddingModelBase:
+ """Base class for embedding models."""
model_name: str
"""The embedding model name"""
@@ -20,6 +22,14 @@ ... | https://raw.githubusercontent.com/agentscope-ai/agentscope/HEAD/src/agentscope/embedding/_embedding_base.py |
Write docstrings describing each step | # -*- coding: utf-8 -*-
from datetime import datetime
from ._shared_state import SharedState
class MessageApi(SharedState):
tool_functions: list[str] = [
"send_message",
"delete_message",
"view_messages_between_users",
"search_messages",
"get_all_message_times_with_ids",
... | --- +++ @@ -1,10 +1,12 @@ # -*- coding: utf-8 -*-
+"""The Message API in the ACEBench evaluation."""
from datetime import datetime
from ._shared_state import SharedState
class MessageApi(SharedState):
+ """The message Api in the ACEBench evaluation."""
tool_functions: list[str] = [
"send_mes... | https://raw.githubusercontent.com/agentscope-ai/agentscope/HEAD/src/agentscope/evaluate/_ace_benchmark/_ace_tools_api/_message_api.py |
Fill in missing docstrings in my code | # -*- coding: utf-8 -*-
# type: ignore
# pylint: disable=too-many-lines
# pylint: disable=too-many-statements
# pylint: disable=too-many-branches
# pylint: disable=too-many-statements
# pylint: disable=too-many-return-statements
from datetime import datetime, timedelta
class TravelApi:
tool_functions: list[str]... | --- +++ @@ -5,11 +5,17 @@ # pylint: disable=too-many-branches
# pylint: disable=too-many-statements
# pylint: disable=too-many-return-statements
+"""The travel API for the ACEBench simulation tools in AgentScope."""
from datetime import datetime, timedelta
class TravelApi:
+ """旅行预订系统类。
+
+ 提供航班查询、用户认证、... | https://raw.githubusercontent.com/agentscope-ai/agentscope/HEAD/src/agentscope/evaluate/_ace_benchmark/_ace_tools_api/_travel_api.py |
Help me comply with documentation standards | # -*- coding: utf-8 -*-
from functools import wraps
from typing import Callable, Any
from ._ace_tools_api import (
ReminderApi,
FoodPlatformApi,
TravelApi,
MessageApi,
)
from ...message import TextBlock
from ...tool import ToolResponse
def _tool_function_wrapper(get_tool_function: Callable) -> Callab... | --- +++ @@ -1,4 +1,5 @@ # -*- coding: utf-8 -*-
+"""The Chinese tools for ACEBench evaluation."""
from functools import wraps
from typing import Callable, Any
@@ -13,13 +14,16 @@
def _tool_function_wrapper(get_tool_function: Callable) -> Callable:
+ """Wrap the tool function result to be ToolResponse."""
... | https://raw.githubusercontent.com/agentscope-ai/agentscope/HEAD/src/agentscope/evaluate/_ace_benchmark/_ace_tools_zh.py |
Generate helpful docstrings for debugging | # -*- coding: utf-8 -*-
from collections import defaultdict
from typing import Sequence
from opentelemetry import baggage
from opentelemetry.sdk.trace import ReadableSpan
from opentelemetry.sdk.trace.export import SpanExporter, SpanExportResult
from ...tracing._attributes import SpanAttributes, OperationNameValues
... | --- +++ @@ -1,4 +1,6 @@ # -*- coding: utf-8 -*-
+"""An in memory exporter of OpenTelemetry traces for AgentScope evaluator, used
+to record the token usage during evaluation."""
from collections import defaultdict
from typing import Sequence
@@ -10,13 +12,26 @@
class _InMemoryExporter(SpanExporter):
+ """An ... | https://raw.githubusercontent.com/agentscope-ai/agentscope/HEAD/src/agentscope/evaluate/_evaluator/_in_memory_exporter.py |
Add docstrings to existing functions | # -*- coding: utf-8 -*-
from abc import ABC, abstractmethod
from typing import Generator
from ._task import Task
class BenchmarkBase(ABC):
name: str
"""The name of the benchmark."""
description: str
"""The description of the benchmark."""
def __init__(self, name: str, description: str) -> None... | --- +++ @@ -1,4 +1,5 @@ # -*- coding: utf-8 -*-
+"""The base class for benchmark evaluation."""
from abc import ABC, abstractmethod
from typing import Generator
@@ -6,6 +7,7 @@
class BenchmarkBase(ABC):
+ """The base class for benchmark evaluation."""
name: str
"""The name of the benchmark."""
@@... | https://raw.githubusercontent.com/agentscope-ai/agentscope/HEAD/src/agentscope/evaluate/_benchmark_base.py |
Add verbose docstrings with examples | # -*- coding: utf-8 -*-
from datetime import datetime
from typing import Any, Literal
from ._cache_base import EmbeddingCacheBase
from ._embedding_response import EmbeddingResponse
from ._embedding_usage import EmbeddingUsage
from ._embedding_base import EmbeddingModelBase
from ..message import (
VideoBlock,
I... | --- +++ @@ -1,4 +1,5 @@ # -*- coding: utf-8 -*-
+"""The dashscope multimodal embedding model in agentscope."""
from datetime import datetime
from typing import Any, Literal
@@ -14,6 +15,8 @@
class DashScopeMultiModalEmbedding(EmbeddingModelBase):
+ """The DashScope multimodal embedding API, supporting text, ... | https://raw.githubusercontent.com/agentscope-ai/agentscope/HEAD/src/agentscope/embedding/_dashscope_multimodal_embedding.py |
Write docstrings describing functionality | # -*- coding: utf-8 -*-
from .._solution import SolutionOutput
from .._metric_base import MetricBase, MetricResult, MetricType
class ACEProcessAccuracy(MetricBase):
def __init__(
self,
mile_stone: list[str],
) -> None:
super().__init__(
name="process_accuracy",
... | --- +++ @@ -1,15 +1,18 @@ # -*- coding: utf-8 -*-
+"""The ACE benchmark metric implementations in AgentScope."""
from .._solution import SolutionOutput
from .._metric_base import MetricBase, MetricResult, MetricType
class ACEProcessAccuracy(MetricBase):
+ """The ace benchmark process accuracy metric."""
... | https://raw.githubusercontent.com/agentscope-ai/agentscope/HEAD/src/agentscope/evaluate/_ace_benchmark/_ace_metric.py |
Document functions with detailed explanations | # -*- coding: utf-8 -*-
from ._shared_state import SharedState
class FoodPlatformApi(SharedState):
tool_functions: list[str] = [
"login_food_platform",
"view_logged_in_users",
"check_balance",
"add_food_delivery_order",
"get_products",
"view_orders",
"sear... | --- +++ @@ -1,9 +1,11 @@ # -*- coding: utf-8 -*-
+"""The food platform API in the ACEBench evaluation."""
from ._shared_state import SharedState
class FoodPlatformApi(SharedState):
+ """The food platform Api in the ACEBench evaluation."""
tool_functions: list[str] = [
"login_food_platform",
@... | https://raw.githubusercontent.com/agentscope-ai/agentscope/HEAD/src/agentscope/evaluate/_ace_benchmark/_ace_tools_api/_food_platform_api.py |
Generate consistent docstrings | # -*- coding: utf-8 -*-
import asyncio
from datetime import datetime
from typing import Any
from agentscope.agent import AgentBase
class ExampleAgent(AgentBase):
def __init__(self, name: str) -> None:
super().__init__()
self.name = name
async def reply(self, *args: Any, **kwargs: Any) -> No... | --- +++ @@ -1,4 +1,11 @@ # -*- coding: utf-8 -*-
+"""
+Concurrent Agents
+===================================
+With the help of asynchronous programming, the concurrent agents can be executed by ``asyncio.gather`` in Python.
+
+A simple example is shown below, where two agents are created and executed concurrently.
+""... | https://raw.githubusercontent.com/agentscope-ai/agentscope/HEAD/docs/tutorial/en/src/workflow_concurrent_agents.py |
Add standardized docstrings across the file | # -*- coding: utf-8 -*-
import asyncio
import io
import json
import os
from asyncio import Task, Queue
from collections import OrderedDict
from copy import deepcopy
from typing import Callable, Any
import base64
import shortuuid
import numpy as np
from typing_extensions import deprecated
from ._agent_meta import _Agen... | --- +++ @@ -1,4 +1,5 @@ # -*- coding: utf-8 -*-
+"""The agent base class in agentscope."""
import asyncio
import io
import json
@@ -27,6 +28,7 @@
class AgentBase(StateModule, metaclass=_AgentMeta):
+ """Base class for asynchronous agents."""
id: str
"""The agent's unique identifier, generated usin... | https://raw.githubusercontent.com/agentscope-ai/agentscope/HEAD/src/agentscope/agent/_agent_base.py |
Add docstrings to my Python code | # -*- coding: utf-8 -*-
from abc import abstractmethod
from typing import Any, Callable
from .._metric_base import MetricResult
from .._solution import SolutionOutput
from ...agent import AgentBase
from ...types import JSONSerializableObject
class EvaluatorStorageBase:
@abstractmethod
def save_solution_resu... | --- +++ @@ -1,4 +1,6 @@ # -*- coding: utf-8 -*-
+"""The evaluator storage base class for storing solution and evaluation
+results."""
from abc import abstractmethod
from typing import Any, Callable
@@ -9,6 +11,8 @@
class EvaluatorStorageBase:
+ """Used to store the solution results and evaluation results to ... | https://raw.githubusercontent.com/agentscope-ai/agentscope/HEAD/src/agentscope/evaluate/_evaluator_storage/_evaluator_storage_base.py |
Write docstrings including parameters and return values | # -*- coding: utf-8 -*-
import asyncio
from typing import Callable, Awaitable, Coroutine, Any
from ._in_memory_exporter import _InMemoryExporter
from .._benchmark_base import BenchmarkBase
from .._evaluator._evaluator_base import EvaluatorBase
from .._solution import SolutionOutput
from .._task import Task
from .._eva... | --- +++ @@ -1,4 +1,5 @@ # -*- coding: utf-8 -*-
+"""The evaluator base class in agentscope."""
import asyncio
from typing import Callable, Awaitable, Coroutine, Any
@@ -11,6 +12,7 @@
def _check_ray_available() -> None:
+ """Check if ray is available and raise ImportError if not."""
try:
import ... | https://raw.githubusercontent.com/agentscope-ai/agentscope/HEAD/src/agentscope/evaluate/_evaluator/_ray_evaluator.py |
Turn comments into proper docstrings | # -*- coding: utf-8 -*-
from typing import Callable, Awaitable, Coroutine, Any
from ._evaluator_base import EvaluatorBase
from ._in_memory_exporter import _InMemoryExporter
from .._evaluator_storage import EvaluatorStorageBase
from .._task import Task
from .._solution import SolutionOutput
from .._benchmark_base impor... | --- +++ @@ -1,4 +1,6 @@ # -*- coding: utf-8 -*-
+"""General evaluator implementation in AgentScope, which is easy to debug
+compared to the RayEvaluator."""
from typing import Callable, Awaitable, Coroutine, Any
from ._evaluator_base import EvaluatorBase
@@ -10,6 +12,7 @@
class GeneralEvaluator(EvaluatorBase):
... | https://raw.githubusercontent.com/agentscope-ai/agentscope/HEAD/src/agentscope/evaluate/_evaluator/_general_evaluator.py |
Generate docstrings for exported functions | # -*- coding: utf-8 -*-
from dataclasses import dataclass, field
from typing import Any
from ._solution import SolutionOutput
from ._metric_base import MetricBase, MetricResult
from ..types._json import JSONSerializableObject
@dataclass
class Task:
id: str
"""The unique identifier for the task."""
inpu... | --- +++ @@ -1,4 +1,5 @@ # -*- coding: utf-8 -*-
+"""The base class for task in evaluation."""
from dataclasses import dataclass, field
from typing import Any
@@ -9,6 +10,7 @@
@dataclass
class Task:
+ """The base class for task in evaluation."""
id: str
"""The unique identifier for the task."""
@@ ... | https://raw.githubusercontent.com/agentscope-ai/agentscope/HEAD/src/agentscope/evaluate/_task.py |
Improve my code by adding docstrings | # -*- coding: utf-8 -*-
from dataclasses import dataclass, field
from typing import Any
from ..message import (
ToolResultBlock,
ToolUseBlock,
TextBlock,
)
from ..types._json import JSONSerializableObject
from .._utils._mixin import DictMixin
@dataclass
class SolutionOutput(DictMixin):
success: boo... | --- +++ @@ -1,4 +1,5 @@ # -*- coding: utf-8 -*-
+"""Solution class for evaluation tasks."""
from dataclasses import dataclass, field
from typing import Any
@@ -14,6 +15,7 @@
@dataclass
class SolutionOutput(DictMixin):
+ """The output of a solution in evaluation task"""
success: bool
"""Indicates w... | https://raw.githubusercontent.com/agentscope-ai/agentscope/HEAD/src/agentscope/evaluate/_solution.py |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.