instruction
stringclasses
100 values
code
stringlengths
78
193k
response
stringlengths
259
170k
file
stringlengths
59
203
Add standardized docstrings across the file
from __future__ import annotations import asyncio import json from typing import Any from sqlalchemy import ( TIMESTAMP, Column, ForeignKey, Index, Integer, MetaData, String, Table, Text, delete, insert, select, text as sql_text, update, ) from sqlalchemy.ext.a...
--- +++ @@ -1,3 +1,25 @@+"""SQLAlchemy-powered Session backend. + +Usage:: + + from agents.extensions.memory import SQLAlchemySession + + # Create from SQLAlchemy URL (uses asyncpg driver under the hood for Postgres) + session = SQLAlchemySession.from_url( + session_id="user-123", + url="postgres...
https://raw.githubusercontent.com/openai/openai-agents-python/HEAD/src/agents/extensions/memory/sqlalchemy_session.py
Add well-formatted docstrings
from __future__ import annotations import logging from typing import TYPE_CHECKING, Any, Callable, Literal from openai import AsyncOpenAI from ..models._openai_shared import get_default_openai_client from .openai_conversations_session import OpenAIConversationsSession from .session import ( OpenAIResponsesCompac...
--- +++ @@ -27,6 +27,10 @@ def select_compaction_candidate_items( items: list[TResponseInputItem], ) -> list[TResponseInputItem]: + """Select compaction candidate items. + + Excludes user messages and compaction items. + """ def _is_user_message(item: TResponseInputItem) -> bool: if not i...
https://raw.githubusercontent.com/openai/openai-agents-python/HEAD/src/agents/memory/openai_responses_compaction_session.py
Turn comments into proper docstrings
from __future__ import annotations from dataclasses import dataclass from typing import TYPE_CHECKING, Any if TYPE_CHECKING: from .agent import Agent from .guardrail import InputGuardrailResult, OutputGuardrailResult from .items import ModelResponse, RunItem, TResponseInputItem from .run_context impor...
--- +++ @@ -19,6 +19,7 @@ @dataclass class RunErrorDetails: + """Data collected from an agent run when an exception occurs.""" input: str | list[TResponseInputItem] new_items: list[RunItem] @@ -33,6 +34,7 @@ class AgentsException(Exception): + """Base class for all exceptions in the Agents SDK....
https://raw.githubusercontent.com/openai/openai-agents-python/HEAD/src/agents/exceptions.py
Provide docstrings following PEP 257
from __future__ import annotations import copy import dataclasses import json from collections import deque from collections.abc import Callable, Mapping, Sequence from dataclasses import dataclass, field from typing import TYPE_CHECKING, Any, Generic, Literal, Optional, Union, cast from uuid import uuid4 from opena...
--- +++ @@ -1,3 +1,4 @@+"""RunState class for serializing and resuming agent runs with human-in-the-loop support.""" from __future__ import annotations @@ -136,6 +137,19 @@ @dataclass class RunState(Generic[TContext, TAgent]): + """Serializable snapshot of an agent run, including context, usage, and interrup...
https://raw.githubusercontent.com/openai/openai-agents-python/HEAD/src/agents/run_state.py
Add docstrings to improve readability
from __future__ import annotations import json import logging from dataclasses import dataclass, field from typing import TYPE_CHECKING, Any, cast from .._tool_identity import get_tool_call_name, get_tool_call_trace_name if TYPE_CHECKING: from ..run_config import CallModelData, ModelInputData logger = logging....
--- +++ @@ -1,3 +1,29 @@+"""Built-in call_model_input_filter that trims large tool outputs from older turns. + +Agentic applications often accumulate large tool outputs (search results, code execution +output, error analyses) that consume significant tokens but lose relevance as the +conversation progresses. This modul...
https://raw.githubusercontent.com/openai/openai-agents-python/HEAD/src/agents/extensions/tool_output_trimmer.py
Provide docstrings following PEP 257
from __future__ import annotations from dataclasses import dataclass, field, fields from typing import TYPE_CHECKING, Any, cast from openai.types.responses import ResponseFunctionToolCall from ._tool_identity import get_tool_call_namespace, tool_trace_name from .agent_tool_state import get_agent_tool_state_scope, se...
--- +++ @@ -34,6 +34,7 @@ @dataclass class ToolContext(RunContextWrapper[TContext]): + """The context of a tool call.""" tool_name: str = field(default_factory=_assert_must_pass_tool_name) """The name of the tool being invoked.""" @@ -72,6 +73,7 @@ _approvals: dict[str, _ApprovalRecord] | None...
https://raw.githubusercontent.com/openai/openai-agents-python/HEAD/src/agents/tool_context.py
Please document this code using docstrings
from __future__ import annotations import os from dataclasses import dataclass, field from typing import TYPE_CHECKING, Any, Callable, Generic, Literal, Optional from typing_extensions import NotRequired, TypedDict from .guardrail import InputGuardrail, OutputGuardrail from .handoffs import HandoffHistoryMapper, Han...
--- +++ @@ -28,12 +28,14 @@ def _default_trace_include_sensitive_data() -> bool: + """Return the default for trace_include_sensitive_data based on environment.""" val = os.getenv("OPENAI_AGENTS_TRACE_INCLUDE_SENSITIVE_DATA", "true") return val.strip().lower() in ("1", "true", "yes", "on") @datacla...
https://raw.githubusercontent.com/openai/openai-agents-python/HEAD/src/agents/run_config.py
Improve documentation using docstrings
from __future__ import annotations from dataclasses import dataclass, field from typing import TYPE_CHECKING, Any, Generic from typing_extensions import TypeVar from ._tool_identity import ( FunctionToolLookupKey, get_function_tool_approval_keys, get_function_tool_lookup_key, is_reserved_synthetic_to...
--- +++ @@ -27,6 +27,11 @@ @dataclass(eq=False) class _ApprovalRecord: + """Tracks approval/rejection state for a tool. + + ``approved`` and ``rejected`` are either booleans (permanent allow/deny) + or lists of call IDs when approval is scoped to specific tool calls. + """ approved: bool | list[st...
https://raw.githubusercontent.com/openai/openai-agents-python/HEAD/src/agents/run_context.py
Add docstrings explaining edge cases
from __future__ import annotations import asyncio import inspect from collections.abc import Awaitable, Callable, Mapping, Sequence from typing import Any, Literal, cast from openai.types.responses import ( ResponseCompactionItem, ResponseComputerToolCall, ResponseCustomToolCall, ResponseFileSearchToo...
--- +++ @@ -233,6 +233,7 @@ ] | None = None, ) -> SingleStepResult: + """Finalize a turn once final output is known and run end hooks.""" final_output_hooks = run_final_output_hooks_fn or run_final_output_hooks await final_output_hooks(agent, hooks, context_wrapper, final_output) @@ -265,6 +266...
https://raw.githubusercontent.com/openai/openai-agents-python/HEAD/src/agents/run_internal/turn_resolution.py
Create Google-style docstrings for my code
from .config import TracingConfig from .context import TraceCtxManager from .create import ( agent_span, custom_span, function_span, generation_span, get_current_span, get_current_trace, guardrail_span, handoff_span, mcp_tools_span, response_span, speech_group_span, speec...
--- +++ @@ -83,16 +83,28 @@ def add_trace_processor(span_processor: TracingProcessor) -> None: + """ + Adds a new trace processor. This processor will receive all traces/spans. + """ get_trace_provider().register_processor(span_processor) def set_trace_processors(processors: list[TracingProcessor...
https://raw.githubusercontent.com/openai/openai-agents-python/HEAD/src/agents/tracing/__init__.py
Write docstrings for backend logic
from __future__ import annotations import asyncio import inspect from collections.abc import Mapping from typing import Any def _get_awaitable_to_wait_on(awaitable: Any) -> Any | None: if inspect.iscoroutine(awaitable): return awaitable.cr_await if inspect.isgenerator(awaitable): return awai...
--- +++ @@ -1,3 +1,11 @@+"""Best-effort progress inspection for cancelled function-tool tasks. + +These helpers prefer public coroutine introspection first, then fall back to a +small set of private asyncio attributes for patterns that still hide their +driving tasks or deadlines (`Task._fut_waiter`, gather `_children`...
https://raw.githubusercontent.com/openai/openai-agents-python/HEAD/src/agents/run_internal/_asyncio_progress.py
Create docstrings for API functions
from __future__ import annotations import json import math import os import queue import random import threading import time from functools import cached_property from typing import Any import httpx from ..logger import logger from .processor_interface import TracingExporter, TracingProcessor from .spans import Span...
--- +++ @@ -19,6 +19,7 @@ class ConsoleSpanExporter(TracingExporter): + """Prints the traces and spans to the console.""" def export(self, items: list[Trace | Span[Any]]) -> None: for item in items: @@ -50,6 +51,19 @@ base_delay: float = 1.0, max_delay: float = 30.0, ): + ...
https://raw.githubusercontent.com/openai/openai-agents-python/HEAD/src/agents/tracing/processors.py
Generate consistent documentation across files
from __future__ import annotations import logging import os import threading import uuid from abc import ABC, abstractmethod from datetime import datetime, timezone from typing import Any from ..logger import logger from .config import TracingConfig from .processor_interface import TracingProcessor from .scope import...
--- +++ @@ -17,6 +17,7 @@ def _safe_debug(message: str) -> None: + """Best-effort debug logging that tolerates closed streams during shutdown.""" def _has_closed_stream_handler(log: logging.Logger) -> bool: current: logging.Logger | None = log @@ -41,6 +42,9 @@ class SynchronousMultiTracingPr...
https://raw.githubusercontent.com/openai/openai-agents-python/HEAD/src/agents/tracing/provider.py
Write docstrings describing functionality
from __future__ import annotations from typing import Any from .config import TracingConfig from .create import get_current_trace, trace from .traces import ( Trace, TraceState, _hash_tracing_api_key, _trace_id_was_started, reattach_trace, ) def _get_tracing_api_key(tracing: TracingConfig | None...
--- +++ @@ -55,6 +55,7 @@ trace_state: TraceState | None = None, reattach_resumed_trace: bool = False, ) -> Trace | None: + """Return a trace object for this run when one is not already active.""" current_trace = get_current_trace() if current_trace: return None @@ -88,6 +89,7 @@ cla...
https://raw.githubusercontent.com/openai/openai-agents-python/HEAD/src/agents/tracing/context.py
Write documentation strings for class attributes
from __future__ import annotations from collections.abc import Sequence from typing import Any from openai.types.responses import ResponseFunctionToolCall from ..agent import Agent from ..items import ItemHelpers, RunItem, ToolApprovalItem, ToolCallOutputItem, TResponseInputItem from .items import ReasoningItemIdPo...
--- +++ @@ -1,3 +1,8 @@+""" +Helpers for approval handling within the run loop. Keep only execution-time utilities that +coordinate approval placeholders and normalization; public APIs should stay in run.py or +peer modules. +""" from __future__ import annotations @@ -24,6 +29,7 @@ call_id: str | None, me...
https://raw.githubusercontent.com/openai/openai-agents-python/HEAD/src/agents/run_internal/approvals.py
Write clean docstrings for readability
from __future__ import annotations import asyncio from typing import Any from ..agent import Agent from ..exceptions import InputGuardrailTripwireTriggered, OutputGuardrailTripwireTriggered from ..guardrail import ( InputGuardrail, InputGuardrailResult, OutputGuardrail, OutputGuardrailResult, ) from ....
--- +++ @@ -59,6 +59,7 @@ streamed_result: RunResultStreaming, parent_span: Span[Any], ) -> None: + """Run guardrails concurrently and stream results into the queue.""" queue = streamed_result._input_guardrail_queue guardrail_tasks = [ @@ -104,6 +105,7 @@ input: str | list[TResponseInputIte...
https://raw.githubusercontent.com/openai/openai-agents-python/HEAD/src/agents/run_internal/guardrails.py
Write clean docstrings for readability
import abc from typing import TYPE_CHECKING, Any if TYPE_CHECKING: from .spans import Span from .traces import Trace class TracingProcessor(abc.ABC): @abc.abstractmethod def on_trace_start(self, trace: "Trace") -> None: pass @abc.abstractmethod def on_trace_end(self, trace: "Trace")...
--- +++ @@ -7,34 +7,136 @@ class TracingProcessor(abc.ABC): + """Interface for processing and monitoring traces and spans in the OpenAI Agents system. + + This abstract class defines the interface that all tracing processors must implement. + Processors receive notifications when traces and spans start and...
https://raw.githubusercontent.com/openai/openai-agents-python/HEAD/src/agents/tracing/processor_interface.py
Write proper docstrings for these functions
from __future__ import annotations from dataclasses import dataclass from typing import Any, Callable, Generic, Union from typing_extensions import TypedDict from .agent import Agent from .exceptions import MaxTurnsExceeded from .items import ModelResponse, RunItem, TResponseInputItem from .run_context import RunCon...
--- +++ @@ -14,6 +14,7 @@ @dataclass class RunErrorData: + """Snapshot of run data passed to error handlers.""" input: str | list[TResponseInputItem] new_items: list[RunItem] @@ -32,6 +33,7 @@ @dataclass class RunErrorHandlerResult: + """Result returned by an error handler.""" final_outpu...
https://raw.githubusercontent.com/openai/openai-agents-python/HEAD/src/agents/run_error_handlers.py
Write docstrings for backend logic
from __future__ import annotations from collections.abc import Mapping, Sequence from typing import TYPE_CHECKING, Any from ..logger import logger from .config import TracingConfig from .setup import get_trace_provider from .span_data import ( AgentSpanData, CustomSpanData, FunctionSpanData, Generatio...
--- +++ @@ -34,6 +34,30 @@ tracing: TracingConfig | None = None, disabled: bool = False, ) -> Trace: + """ + Create a new trace. The trace will not be started automatically; you should either use + it as a context manager (`with trace(...):`) or call `trace.start()` + `trace.finish()` + manually. ...
https://raw.githubusercontent.com/openai/openai-agents-python/HEAD/src/agents/tracing/create.py
Document this code for team use
from __future__ import annotations from typing import Any, cast from ..agent import Agent from ..agent_tool_state import set_agent_tool_state_scope from ..exceptions import UserError from ..guardrail import InputGuardrailResult from ..items import ModelResponse, RunItem, ToolApprovalItem, TResponseInputItem from ..m...
--- +++ @@ -1,3 +1,4 @@+"""Internal helpers for AgentRunner.run.""" from __future__ import annotations @@ -53,6 +54,7 @@ def should_cancel_parallel_model_task_on_input_guardrail_trip() -> bool: + """Return whether an in-flight model task should be cancelled on guardrail trip.""" try: from temp...
https://raw.githubusercontent.com/openai/openai-agents-python/HEAD/src/agents/run_internal/agent_runner_helpers.py
Generate descriptive docstrings automatically
from __future__ import annotations import asyncio import dataclasses import functools import inspect import json from collections.abc import Awaitable, Callable, Mapping, Sequence from typing import TYPE_CHECKING, Any, Literal, TypeVar, cast from openai.types.responses import ResponseFunctionToolCall from openai.typ...
--- +++ @@ -1,3 +1,7 @@+""" +Tool execution helpers for the run pipeline. This module hosts execution-time helpers, +approval plumbing, and payload coercion. Action classes live in tool_actions.py. +""" from __future__ import annotations @@ -158,6 +162,7 @@ @dataclasses.dataclass(frozen=True) class _FunctionToo...
https://raw.githubusercontent.com/openai/openai-agents-python/HEAD/src/agents/run_internal/tool_execution.py
Document all endpoints with docstrings
from __future__ import annotations import ast import asyncio import copy import dataclasses import inspect import json import math import weakref from collections.abc import Awaitable, Mapping from dataclasses import dataclass, field from types import UnionType from typing import ( TYPE_CHECKING, Annotated, ...
--- +++ @@ -85,18 +85,25 @@ class ToolOutputText(BaseModel): + """Represents a tool output that should be sent to the model as text.""" type: Literal["text"] = "text" text: str class ToolOutputTextDict(TypedDict, total=False): + """TypedDict variant for text tool outputs.""" type: Lite...
https://raw.githubusercontent.com/openai/openai-agents-python/HEAD/src/agents/tool.py
Replace inline comments with docstrings
from __future__ import annotations import asyncio import dataclasses import inspect import json from typing import TYPE_CHECKING, Any, Literal, cast from openai.types.responses import ResponseComputerToolCall from openai.types.responses.response_input_item_param import ( ComputerCallOutputAcknowledgedSafetyCheck...
--- +++ @@ -1,3 +1,7 @@+""" +Action executors used by the run loop. This module only houses XXXAction classes; helper +functions and approval plumbing live in tool_execution.py. +""" from __future__ import annotations @@ -67,6 +71,7 @@ def _serialize_trace_payload(payload: Any) -> str: + """Serialize tool p...
https://raw.githubusercontent.com/openai/openai-agents-python/HEAD/src/agents/run_internal/tool_actions.py
Add docstrings following best practices
from __future__ import annotations import json from collections.abc import Sequence from typing import Any, Literal, cast from openai.types.responses import ResponseFunctionToolCall from pydantic import BaseModel from ..agent_tool_state import drop_agent_tool_run_result from ..items import ItemHelpers, RunItem, Too...
--- +++ @@ -1,3 +1,7 @@+""" +Item utilities for the run pipeline. Hosts input normalization helpers and lightweight builders +for synthetic run items or IDs used during tool execution. Internal use only. +""" from __future__ import annotations @@ -49,6 +53,7 @@ def copy_input_items(value: str | list[TResponseI...
https://raw.githubusercontent.com/openai/openai-agents-python/HEAD/src/agents/run_internal/items.py
Add docstrings for better understanding
from __future__ import annotations from dataclasses import dataclass from typing import Any, Literal, Union from typing_extensions import TypeAlias from .agent import Agent from .items import RunItem, TResponseStreamEvent @dataclass class RawResponsesStreamEvent: data: TResponseStreamEvent """The raw resp...
--- +++ @@ -11,6 +11,9 @@ @dataclass class RawResponsesStreamEvent: + """Streaming event from the LLM. These are 'raw' events, i.e. they are directly passed through + from the LLM. + """ data: TResponseStreamEvent """The raw responses streaming event from the LLM.""" @@ -21,6 +24,9 @@ @datacla...
https://raw.githubusercontent.com/openai/openai-agents-python/HEAD/src/agents/stream_events.py
Please document this code using docstrings
from __future__ import annotations import httpx from openai import AsyncOpenAI, DefaultAsyncHttpxClient from ...models import _openai_shared from ..model import STTModel, TTSModel, VoiceModelProvider from .openai_stt import OpenAISTTModel from .openai_tts import OpenAITTSModel _http_client: httpx.AsyncClient | None ...
--- +++ @@ -25,6 +25,7 @@ class OpenAIVoiceModelProvider(VoiceModelProvider): + """A voice model provider that uses OpenAI models.""" def __init__( self, @@ -35,6 +36,18 @@ organization: str | None = None, project: str | None = None, ) -> None: + """Create a new OpenA...
https://raw.githubusercontent.com/openai/openai-agents-python/HEAD/src/agents/voice/models/openai_model_provider.py
Document helper functions with docstrings
from __future__ import annotations import abc from collections.abc import AsyncIterator from typing import Any from ..agent import Agent from ..items import TResponseInputItem from ..result import RunResultStreaming from ..run import Runner class VoiceWorkflowBase(abc.ABC): @abc.abstractmethod def run(self...
--- +++ @@ -11,12 +11,32 @@ class VoiceWorkflowBase(abc.ABC): + """ + A base class for a voice workflow. You must implement the `run` method. A "workflow" is any + code you want, that receives a transcription and yields text that will be turned into speech + by a text-to-speech model. + In most cases...
https://raw.githubusercontent.com/openai/openai-agents-python/HEAD/src/agents/voice/workflow.py
Write reusable docstrings
from __future__ import annotations import abc import contextvars from typing import Any, Generic, TypeVar from typing_extensions import TypedDict from ..logger import logger from . import util from .processor_interface import TracingProcessor from .scope import Scope from .span_data import SpanData TSpanData = Type...
--- +++ @@ -16,34 +16,104 @@ class SpanError(TypedDict): + """Represents an error that occurred during span execution. + + Attributes: + message: A human-readable error description + data: Optional dictionary containing additional error context + """ message: str data: dict[str, A...
https://raw.githubusercontent.com/openai/openai-agents-python/HEAD/src/agents/tracing/spans.py
Improve documentation using docstrings
from __future__ import annotations import dataclasses from dataclasses import dataclass from typing import Any from openai.types.responses import ResponseComputerToolCall, ResponseFunctionToolCall from openai.types.responses.response_output_item import LocalShellCall, McpApprovalRequest from ..agent import Agent, T...
--- +++ @@ -1,3 +1,7 @@+""" +Internal step/result data structures used by the run loop orchestration. +These types are not part of the public SDK surface. +""" from __future__ import annotations @@ -43,6 +47,7 @@ class QueueCompleteSentinel: + """Sentinel used to signal completion when streaming run loop re...
https://raw.githubusercontent.com/openai/openai-agents-python/HEAD/src/agents/run_internal/run_steps.py
Generate docstrings for exported functions
from __future__ import annotations import asyncio import dataclasses as _dc import json from collections.abc import Awaitable, Callable, Mapping from typing import Any, TypeVar, cast from openai.types.responses import Response, ResponseCompletedEvent, ResponseOutputItemDoneEvent from openai.types.responses.response_...
--- +++ @@ -1,3 +1,7 @@+""" +Run-loop orchestration helpers used by the Agent runner. This module coordinates tool execution, +approvals, and turn processing; all symbols here are internal and not part of the public SDK. +""" from __future__ import annotations @@ -410,6 +414,7 @@ *, is_resumed_state: bool...
https://raw.githubusercontent.com/openai/openai-agents-python/HEAD/src/agents/run_internal/run_loop.py
Document helper functions with docstrings
from __future__ import annotations import asyncio import base64 import io import wave from dataclasses import dataclass from ..exceptions import UserError from .imports import np, npt DEFAULT_SAMPLE_RATE = 24000 def _buffer_to_audio_file( buffer: npt.NDArray[np.int16 | np.float32 | np.float64], frame_rate:...
--- +++ @@ -39,6 +39,7 @@ @dataclass class AudioInput: + """Static audio to be used as input for the VoicePipeline.""" buffer: npt.NDArray[np.int16 | np.float32] """ @@ -55,9 +56,11 @@ """The number of channels in the audio data. Defaults to 1.""" def to_audio_file(self) -> tuple[str, io.By...
https://raw.githubusercontent.com/openai/openai-agents-python/HEAD/src/agents/voice/input.py
Write docstrings for utility functions
from __future__ import annotations from typing import Any, get_args, get_origin from .._tool_identity import get_function_tool_trace_name from ..agent import Agent from ..items import ( HandoffCallItem, ToolCallItem, ToolCallItemTypes, ToolCallOutputItem, ToolSearchCallItem, ToolSearchOutputI...
--- +++ @@ -1,3 +1,7 @@+""" +Tool-use tracking utilities. Hosts AgentToolUseTracker and helpers to serialize/deserialize +its state plus lightweight tool-call type utilities. Internal use only. +""" from __future__ import annotations @@ -40,6 +44,7 @@ class AgentToolUseTracker: + """Track which tools an age...
https://raw.githubusercontent.com/openai/openai-agents-python/HEAD/src/agents/run_internal/tool_use_tracker.py
Turn comments into proper docstrings
from __future__ import annotations from collections.abc import Mapping from dataclasses import field from typing import Annotated, Any from openai.types.completion_usage import CompletionTokensDetails, PromptTokensDetails from openai.types.responses.response_usage import InputTokensDetails, OutputTokensDetails from p...
--- +++ @@ -11,6 +11,7 @@ def deserialize_usage(usage_data: Mapping[str, Any]) -> Usage: + """Rebuild a Usage object from serialized JSON data.""" input_tokens_details_raw = usage_data.get("input_tokens_details") output_tokens_details_raw = usage_data.get("output_tokens_details") input_details = _...
https://raw.githubusercontent.com/openai/openai-agents-python/HEAD/src/agents/usage.py
Please document this code using docstrings
from __future__ import annotations import asyncio import dataclasses as _dc import inspect import json from collections.abc import Awaitable, Callable, Hashable, Mapping, Sequence from typing import Any, TypeVar, cast from openai.types.responses import ResponseFunctionToolCall from openai.types.responses.response_inp...
--- +++ @@ -64,6 +64,7 @@ def _hashable_identity_value(value: Any) -> Hashable | None: + """Convert a tool call field into a stable, hashable representation.""" if value is None: return None if isinstance(value, (dict, list, tuple)): @@ -77,6 +78,7 @@ def _tool_call_identity(raw: Any) -> t...
https://raw.githubusercontent.com/openai/openai-agents-python/HEAD/src/agents/run_internal/tool_planning.py
Generate docstrings for this script
from __future__ import annotations import abc import contextvars import hashlib import threading from collections import OrderedDict from collections.abc import Mapping from dataclasses import dataclass, field from typing import Any from ..logger import logger from . import util from .processor_interface import Traci...
--- +++ @@ -16,6 +16,36 @@ class Trace(abc.ABC): + """A complete end-to-end workflow containing related spans and metadata. + + A trace represents a logical workflow or operation (e.g., "Customer Service Query" + or "Code Generation") and contains all the spans (individual operations) that occur + durin...
https://raw.githubusercontent.com/openai/openai-agents-python/HEAD/src/agents/tracing/traces.py
Add docstrings for better understanding
from __future__ import annotations from dataclasses import dataclass from typing import Literal, Union from typing_extensions import TypeAlias from .imports import np, npt @dataclass class VoiceStreamEventAudio: data: npt.NDArray[np.int16 | np.float32] | None """The audio data.""" type: Literal["voic...
--- +++ @@ -10,6 +10,7 @@ @dataclass class VoiceStreamEventAudio: + """Streaming event from the VoicePipeline""" data: npt.NDArray[np.int16 | np.float32] | None """The audio data.""" @@ -20,6 +21,7 @@ @dataclass class VoiceStreamEventLifecycle: + """Streaming event from the VoicePipeline""" ...
https://raw.githubusercontent.com/openai/openai-agents-python/HEAD/src/agents/voice/events.py
Help me add docstrings to my project
import re from typing import Callable def get_sentence_based_splitter( min_sentence_length: int = 20, ) -> Callable[[str], tuple[str, str]]: def sentence_based_text_splitter(text_buffer: str) -> tuple[str, str]: sentences = re.split(r"(?<=[.!?])\s+", text_buffer.strip()) if len(sentences) >= ...
--- +++ @@ -5,8 +5,27 @@ def get_sentence_based_splitter( min_sentence_length: int = 20, ) -> Callable[[str], tuple[str, str]]: + """Returns a function that splits text into chunks based on sentence boundaries. + + Args: + min_sentence_length: The minimum length of a sentence to be included in a chun...
https://raw.githubusercontent.com/openai/openai-agents-python/HEAD/src/agents/voice/utils.py
Add docstrings explaining edge cases
from __future__ import annotations import inspect from collections.abc import Awaitable from dataclasses import dataclass, field from typing import TYPE_CHECKING, Any, Callable, Generic, Literal, overload from typing_extensions import TypedDict, TypeVar from .exceptions import UserError from .tool_context import Too...
--- +++ @@ -17,6 +17,7 @@ @dataclass class ToolInputGuardrailResult: + """The result of a tool input guardrail run.""" guardrail: ToolInputGuardrail[Any] """The guardrail that was run.""" @@ -27,6 +28,7 @@ @dataclass class ToolOutputGuardrailResult: + """The result of a tool output guardrail run...
https://raw.githubusercontent.com/openai/openai-agents-python/HEAD/src/agents/tool_guardrails.py
Generate consistent documentation across files
from __future__ import annotations import asyncio import inspect from typing import Any from ..agent import Agent from ..agent_output import AgentOutputSchema, AgentOutputSchemaBase from ..exceptions import UserError from ..handoffs import Handoff, handoff from ..items import TResponseInputItem from ..lifecycle impor...
--- +++ @@ -30,6 +30,7 @@ def validate_run_hooks( hooks: RunHooksBase[Any, Agent[Any]] | AgentHooksBase[Any, Agent[Any]] | Any | None, ) -> RunHooks[Any]: + """Normalize hooks input and enforce RunHooks type.""" if hooks is None: return RunHooks[Any]() input_hook_type = type(hooks).__name__ ...
https://raw.githubusercontent.com/openai/openai-agents-python/HEAD/src/agents/run_internal/turn_preparation.py
Create structured documentation for my script
from __future__ import annotations import asyncio from ..exceptions import UserError from ..logger import logger from ..tracing import TraceCtxManager from .input import AudioInput, StreamedAudioInput from .model import STTModel, TTSModel from .pipeline_config import VoicePipelineConfig from .result import StreamedAu...
--- +++ @@ -13,6 +13,11 @@ class VoicePipeline: + """An opinionated voice agent pipeline. It works in three steps: + 1. Transcribe audio input into text. + 2. Run the provided `workflow`, which produces a sequence of text responses. + 3. Convert the text responses into streaming audio output. + """ ...
https://raw.githubusercontent.com/openai/openai-agents-python/HEAD/src/agents/voice/pipeline.py
Write docstrings describing functionality
from __future__ import annotations from collections.abc import Sequence from dataclasses import dataclass, field from typing import Any, cast from ..items import ( ItemHelpers, ModelResponse, RunItem, TResponseInputItem, _output_item_to_input_item, ) from ..logger import logger from ..models.fake...
--- +++ @@ -1,3 +1,7 @@+""" +Conversation-state helpers used during agent runs. This module should only host internal +tracking and normalization logic for conversation-aware execution, not public-facing APIs. +""" from __future__ import annotations @@ -29,6 +33,7 @@ def _normalize_server_item_id(value: Any) -...
https://raw.githubusercontent.com/openai/openai-agents-python/HEAD/src/agents/run_internal/oai_conversation.py
Write docstrings for backend logic
from __future__ import annotations import atexit import threading from typing import TYPE_CHECKING if TYPE_CHECKING: from .provider import TraceProvider GLOBAL_TRACE_PROVIDER: TraceProvider | None = None _GLOBAL_TRACE_PROVIDER_LOCK = threading.Lock() _SHUTDOWN_HANDLER_REGISTERED = False def _shutdown_global_tr...
--- +++ @@ -19,6 +19,7 @@ def set_trace_provider(provider: TraceProvider) -> None: + """Set the global trace provider used by tracing utilities.""" global GLOBAL_TRACE_PROVIDER global _SHUTDOWN_HANDLER_REGISTERED @@ -30,6 +31,11 @@ def get_trace_provider() -> TraceProvider: + """Get the global...
https://raw.githubusercontent.com/openai/openai-agents-python/HEAD/src/agents/tracing/setup.py
Add docstrings for internal functions
from __future__ import annotations import abc from collections.abc import AsyncIterator from dataclasses import dataclass from typing import Any, Callable, Literal from .imports import np, npt from .input import AudioInput, StreamedAudioInput from .utils import get_sentence_based_splitter DEFAULT_TTS_INSTRUCTIONS = ...
--- +++ @@ -20,6 +20,7 @@ @dataclass class TTSModelSettings: + """Settings for a TTS model.""" voice: TTSVoice | None = None """ @@ -61,30 +62,47 @@ class TTSModel(abc.ABC): + """A text-to-speech model that can convert text into audio output.""" @property @abc.abstractmethod de...
https://raw.githubusercontent.com/openai/openai-agents-python/HEAD/src/agents/voice/model.py
Expand my code with proper documentation strings
from __future__ import annotations import asyncio import base64 from collections import deque from collections.abc import AsyncIterator from typing import Any from ..exceptions import UserError from ..logger import logger from ..tracing import Span, SpeechGroupSpanData, speech_group_span, speech_span from ..tracing.u...
--- +++ @@ -27,6 +27,7 @@ class StreamedAudioResult: + """The output of a `VoicePipeline`. Streams events and audio data as they're generated.""" def __init__( self, @@ -34,6 +35,13 @@ tts_settings: TTSModelSettings, voice_pipeline_config: VoicePipelineConfig, ): + ""...
https://raw.githubusercontent.com/openai/openai-agents-python/HEAD/src/agents/voice/result.py
Document this module using docstrings
from __future__ import annotations import asyncio import copy import inspect import json from collections.abc import Sequence from typing import Any, cast from ..exceptions import UserError from ..items import HandoffOutputItem, ItemHelpers, RunItem, ToolCallOutputItem, TResponseInputItem from ..logger import logger...
--- +++ @@ -1,3 +1,7 @@+""" +Session persistence helpers for the run pipeline. Only internal persistence/retry helpers +live here; public session interfaces stay in higher-level modules. +""" from __future__ import annotations @@ -55,6 +59,20 @@ include_history_in_prepared_input: bool = True, preserve_dro...
https://raw.githubusercontent.com/openai/openai-agents-python/HEAD/src/agents/run_internal/session_persistence.py
Generate docstrings for this script
from __future__ import annotations import abc from collections.abc import Mapping, Sequence from typing import TYPE_CHECKING, Any if TYPE_CHECKING: from openai.types.responses import Response, ResponseInputItemParam class SpanData(abc.ABC): @abc.abstractmethod def export(self) -> dict[str, Any]: ...
--- +++ @@ -9,18 +9,27 @@ class SpanData(abc.ABC): + """ + Represents span data in the trace. + """ @abc.abstractmethod def export(self) -> dict[str, Any]: + """Export the span data as a dictionary.""" pass @property @abc.abstractmethod def type(self) -> str: + ...
https://raw.githubusercontent.com/openai/openai-agents-python/HEAD/src/agents/tracing/span_data.py
Write docstrings for data processing functions
from __future__ import annotations import asyncio from ..items import ( HandoffCallItem, HandoffOutputItem, MCPApprovalRequestItem, MCPApprovalResponseItem, MCPListToolsItem, MessageOutputItem, ReasoningItem, RunItem, ToolApprovalItem, ToolCallItem, ToolCallOutputItem, ...
--- +++ @@ -28,6 +28,7 @@ new_step_items: list[RunItem], queue: asyncio.Queue[StreamEvent | QueueCompleteSentinel], ) -> None: + """Emit run items as streaming events, skipping approval placeholders.""" for item in new_step_items: if isinstance(item, MessageOutputItem): event = R...
https://raw.githubusercontent.com/openai/openai-agents-python/HEAD/src/agents/run_internal/streaming.py
Add verbose docstrings with examples
from collections.abc import AsyncIterator from typing import Literal from openai import AsyncOpenAI from ..model import TTSModel, TTSModelSettings DEFAULT_VOICE: Literal["ash"] = "ash" class OpenAITTSModel(TTSModel): def __init__( self, model: str, openai_client: AsyncOpenAI, ): ...
--- +++ @@ -9,12 +9,19 @@ class OpenAITTSModel(TTSModel): + """A text-to-speech model for OpenAI.""" def __init__( self, model: str, openai_client: AsyncOpenAI, ): + """Create a new OpenAI text-to-speech model. + + Args: + model: The name of the mod...
https://raw.githubusercontent.com/openai/openai-agents-python/HEAD/src/agents/voice/models/openai_tts.py
Add docstrings to improve readability
from __future__ import annotations import asyncio import base64 import json import time from collections.abc import AsyncIterator from dataclasses import dataclass from typing import Any, cast from openai import AsyncOpenAI from ... import _debug from ...exceptions import AgentsException from ...logger import logger...
--- +++ @@ -52,6 +52,9 @@ async def _wait_for_event( event_queue: asyncio.Queue[dict[str, Any]], expected_types: list[str], timeout: float ): + """ + Wait for an event from event_queue whose type is in expected_types within the specified timeout. + """ start_time = time.time() while True: ...
https://raw.githubusercontent.com/openai/openai-agents-python/HEAD/src/agents/voice/models/openai_stt.py
Help me document legacy Python code
# Copyright (c) 2024 Alibaba Inc (authors: Xiang Lyu) # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law ...
--- +++ @@ -29,6 +29,15 @@ def parquet_opener(data, mode='train'): + """ Give url or local file, return file descriptor + Inplace operation. + + Args: + data(Iterable[str]): url or local file list + + Returns: + Iterable[{src, stream}] + """ for sample in data: ...
https://raw.githubusercontent.com/FunAudioLLM/CosyVoice/HEAD/cosyvoice/dataset/processor.py
Generate documentation strings for clarity
# Copyright (c) 2020 Mobvoi Inc (Binbin Zhang) # 2024 Alibaba Inc (authors: Xiang Lyu) # 2025 Alibaba Inc (authors: Xiang Lyu, Bofan Zhou) # # 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...
--- +++ @@ -14,6 +14,7 @@ # See the License for the specific language governing permissions and # limitations under the License. # Modified from ESPnet(https://github.com/espnet/espnet) +"""Unility functions for Transformer.""" import queue import random @@ -53,6 +54,25 @@ def pad_list(xs: List[torch.Tensor],...
https://raw.githubusercontent.com/FunAudioLLM/CosyVoice/HEAD/cosyvoice/utils/common.py
Add docstrings for utility scripts
from __future__ import annotations from typing import Optional import math import torch from torch import nn import torch.nn.functional as F import torchaudio from x_transformers.x_transformers import apply_rotary_pos_emb # raw wav to mel spec class MelSpec(nn.Module): def __init__( self, filt...
--- +++ @@ -1,4 +1,12 @@ +""" +ein notation: +b - batch +n - sequence +nt - text sequence +nw - raw wave length +d - dimension +""" from __future__ import annotations from typing import Optional @@ -526,6 +534,14 @@ class MMDiTBlock(nn.Module): + r""" + modified from diffusers/src/diffusers/models/attent...
https://raw.githubusercontent.com/FunAudioLLM/CosyVoice/HEAD/cosyvoice/flow/DiT/modules.py
Write Python docstrings for this snippet
# Copyright (c) 2021 Mobvoi Inc. (authors: Binbin Zhang) # 2024 Alibaba Inc (authors: Xiang Lyu) # # 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/li...
--- +++ @@ -36,6 +36,9 @@ self.source.set_epoch(epoch) def __iter__(self): + """ Return an iterator over the source dataset processed by the + given processor. + """ assert self.source is not None assert callable(self.f) return self.f(iter(self.source),...
https://raw.githubusercontent.com/FunAudioLLM/CosyVoice/HEAD/cosyvoice/dataset/dataset.py
Write docstrings for utility functions
# Copyright (c) 2019 Shigeki Karita # 2020 Mobvoi Inc (Binbin Zhang) # # 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 ...
--- +++ @@ -12,6 +12,7 @@ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. +"""Decoder self-attention layer definition.""" from typing import Optional, Tuple import torch @@ -19,6 +20,2...
https://raw.githubusercontent.com/FunAudioLLM/CosyVoice/HEAD/cosyvoice/transformer/decoder_layer.py
Create docstrings for API functions
# Copyright (c) 2021 Mobvoi Inc (Binbin Zhang, Di Wu) # 2022 Xingchen Song (sxc19@mails.tsinghua.edu.cn) # 2024 Alibaba Inc (Xiang Lyu) # # 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 co...
--- +++ @@ -14,6 +14,7 @@ # See the License for the specific language governing permissions and # limitations under the License. # Modified from ESPnet(https://github.com/espnet/espnet) +"""Encoder definition.""" from typing import Tuple import torch @@ -54,6 +55,37 @@ use_dynamic_left_chunk: bool = False...
https://raw.githubusercontent.com/FunAudioLLM/CosyVoice/HEAD/cosyvoice/transformer/encoder.py
Help me write clear docstrings
# Copyright (c) 2020 Mobvoi Inc. (authors: Binbin Zhang, Di Wu) # 2024 Alibaba Inc (Xiang Lyu) # # 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/lice...
--- +++ @@ -13,6 +13,7 @@ # See the License for the specific language governing permissions and # limitations under the License. # Modified from ESPnet(https://github.com/espnet/espnet) +"""Positonal Encoding Module.""" import math from typing import Tuple, Union @@ -23,12 +24,22 @@ class PositionalEncoding(t...
https://raw.githubusercontent.com/FunAudioLLM/CosyVoice/HEAD/cosyvoice/transformer/embedding.py
Write Python docstrings for this snippet
# Copyright (c) 2021 Mobvoi Inc. (authors: Binbin Zhang, Di Wu) # 2024 Alibaba Inc (Xiang Lyu) # # 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/lice...
--- +++ @@ -13,6 +13,7 @@ # See the License for the specific language governing permissions and # limitations under the License. # Modified from ESPnet(https://github.com/espnet/espnet) +"""Decoder definition.""" from typing import Tuple, List, Optional import torch @@ -30,6 +31,29 @@ class TransformerDecoder...
https://raw.githubusercontent.com/FunAudioLLM/CosyVoice/HEAD/cosyvoice/transformer/decoder.py
Add concise docstrings to each method
# Copyright (c) 2019 Shigeki Karita # 2020 Mobvoi Inc (Binbin Zhang) # # 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 ...
--- +++ @@ -12,18 +12,51 @@ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. +"""Label smoothing module.""" import torch from torch import nn class LabelSmoothingLoss(nn.Module): +...
https://raw.githubusercontent.com/FunAudioLLM/CosyVoice/HEAD/cosyvoice/transformer/label_smoothing_loss.py
Add docstrings to improve readability
# Copyright (c) 2024 Alibaba Inc (authors: Xiang Lyu, Zhihao Du) # 2025 Alibaba Inc (authors: Xiang Lyu, Bofan Zhou) # # 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...
--- +++ @@ -35,6 +35,23 @@ @torch.inference_mode() def forward(self, mu, mask, n_timesteps, temperature=1.0, spks=None, cond=None, prompt_len=0, cache=torch.zeros(1, 80, 0, 2)): + """Forward diffusion + + Args: + mu (torch.Tensor): output of encoder + shape: (batch_siz...
https://raw.githubusercontent.com/FunAudioLLM/CosyVoice/HEAD/cosyvoice/flow/flow_matching.py
Add docstrings to improve collaboration
# Copyright (c) 2024 Alibaba Inc (authors: Xiang Lyu, Zhihao Du) # 2025 Alibaba Inc (authors: Xiang Lyu, Yabin Li, Qihua, Shengqiang Li) # # 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 Lic...
--- +++ @@ -102,6 +102,13 @@ batch: dict, device: torch.device, ) -> Dict[str, Optional[torch.Tensor]]: + """ + Args: + text: (B, L, D) + text_lengths: (B,) + audio: (B, T, N) or (B, T) + audio_lengths: (B,) + """ te...
https://raw.githubusercontent.com/FunAudioLLM/CosyVoice/HEAD/cosyvoice/llm/llm.py
Generate helpful docstrings for debugging
# Copyright (c) 2020 Mobvoi Inc. (authors: Binbin Zhang, Di Wu) # 2024 Alibaba Inc (Xiang Lyu) # # 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/lice...
--- +++ @@ -13,6 +13,7 @@ # See the License for the specific language governing permissions and # limitations under the License. # Modified from ESPnet(https://github.com/espnet/espnet) +"""ConvolutionModule definition.""" from typing import Tuple @@ -22,6 +23,7 @@ class ConvolutionModule(nn.Module): + ""...
https://raw.githubusercontent.com/FunAudioLLM/CosyVoice/HEAD/cosyvoice/transformer/convolution.py
Create documentation strings for testing functions
# Copyright (c) 2019 Shigeki Karita # 2020 Mobvoi Inc (Binbin Zhang) # 2024 Alibaba Inc (authors: Xiang Lyu) # # 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 # # ...
--- +++ @@ -54,6 +54,31 @@ size: int, device: torch.device = torch.device("cpu"), ) -> torch.Tensor: + """Create mask for subsequent steps (size, size). + + This mask is used only in decoder which works in an auto-regressive mode. + This means the current step could only do attention with its...
https://raw.githubusercontent.com/FunAudioLLM/CosyVoice/HEAD/cosyvoice/utils/mask.py
Add structured docstrings to improve clarity
# Copyright (c) 2021 Mobvoi Inc (Binbin Zhang, Di Wu) # 2022 Xingchen Song (sxc19@mails.tsinghua.edu.cn) # 2024 Alibaba Inc (Xiang Lyu) # # 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 co...
--- +++ @@ -14,6 +14,7 @@ # See the License for the specific language governing permissions and # limitations under the License. # Modified from ESPnet(https://github.com/espnet/espnet) +"""Encoder definition.""" from typing import Tuple import torch @@ -34,6 +35,18 @@ class Upsample1D(nn.Module): + """A 1...
https://raw.githubusercontent.com/FunAudioLLM/CosyVoice/HEAD/cosyvoice/transformer/upsample_encoder.py
Document this module using docstrings
# Copyright (c) 2024 Alibaba Inc (authors: Xiang Lyu, Kai Hu) # # 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 applica...
--- +++ @@ -12,6 +12,7 @@ # See the License for the specific language governing permissions and # limitations under the License. +"""HIFI-GAN""" from typing import Dict, Optional, List import numpy as np @@ -43,6 +44,7 @@ class ResBlock(torch.nn.Module): + """Residual block module in HiFiGAN/BigVGAN.""" ...
https://raw.githubusercontent.com/FunAudioLLM/CosyVoice/HEAD/cosyvoice/hifigan/generator.py
Add docstrings that explain logic
# Copyright (c) 2024 Alibaba Inc (authors: Xiang Lyu, Zhihao Du) # # 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 appl...
--- +++ @@ -98,6 +98,10 @@ num_heads=4, act_fn="snake", ): + """ + This decoder requires an input with the same shape of the target. So, if your text content + is shorter or longer than the outputs, please re-sampling it before feeding to the decoder. + """ sup...
https://raw.githubusercontent.com/FunAudioLLM/CosyVoice/HEAD/cosyvoice/flow/decoder.py
Annotate my code with docstrings
# Copyright (c) 2019 Shigeki Karita # 2020 Mobvoi Inc (Binbin Zhang) # 2022 Xingchen Song (sxc19@mails.tsinghua.edu.cn) # 2024 Alibaba Inc (Xiang Lyu) # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the L...
--- +++ @@ -14,6 +14,7 @@ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. +"""Multi-Head Attention layer definition.""" import math from typing import Tuple @@ -23,12 +24,21 @@ cla...
https://raw.githubusercontent.com/FunAudioLLM/CosyVoice/HEAD/cosyvoice/transformer/attention.py
Add docstrings to incomplete code
# Copyright (c) 2020 Mobvoi Inc (Binbin Zhang) # 2022 Ximalaya Inc (Yuguang Yang) # 2024 Alibaba Inc (authors: Xiang Lyu) # # 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 Lice...
--- +++ @@ -25,6 +25,21 @@ class WarmupLR(_LRScheduler): + """The WarmupLR scheduler + + This scheduler is almost same as NoamLR Scheduler except for following + difference: + + NoamLR: + lr = optimizer.lr * model_size ** -0.5 + * min(step ** -0.5, step * warmup_step ** -1.5) + War...
https://raw.githubusercontent.com/FunAudioLLM/CosyVoice/HEAD/cosyvoice/utils/scheduler.py
Write proper docstrings for these functions
import torch import torch.nn as nn import torch.nn.functional as F try: from torch.nn.utils.parametrizations import weight_norm, spectral_norm except ImportError: from torch.nn.utils import weight_norm, spectral_norm from typing import List, Optional, Tuple from einops import rearrange from torchaudio.transform...
--- +++ @@ -41,6 +41,15 @@ fft_sizes: Tuple[int, ...] = (2048, 1024, 512), num_embeddings: Optional[int] = None, ): + """ + Multi-Resolution Discriminator module adapted from https://github.com/descriptinc/descript-audio-codec. + Additionally, it allows incorporating condition...
https://raw.githubusercontent.com/FunAudioLLM/CosyVoice/HEAD/cosyvoice/hifigan/discriminator.py
Document functions with clear intent
# Copyright 2022 Xiaomi Corp. (authors: Fangjun Kuang) # 2023 Nvidia (authors: Yuekai Zhang) # 2023 Recurrent.ai (authors: Songtao Shi) # See LICENSE for clarification regarding multiple authors # # Licensed under the Apache License, Version 2.0 (the "Lic...
--- +++ @@ -14,6 +14,31 @@ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. +""" +This script supports to load dataset from huggingface and sends it to the server +for decoding, in parallel...
https://raw.githubusercontent.com/FunAudioLLM/CosyVoice/HEAD/runtime/triton_trtllm/client_grpc.py
Create Google-style docstrings for my code
# Copyright 2025, NVIDIA CORPORATION & AFFILIATES. All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # * Redistributions of source code must retain the above copyright # notice, this list of con...
--- +++ @@ -37,8 +37,18 @@ class TritonPythonModel: + """Triton Python model for audio tokenization. + + This model takes reference audio input and extracts semantic tokens + using s3tokenizer. + """ def initialize(self, args): + """Initialize the model. + + Args: + args:...
https://raw.githubusercontent.com/FunAudioLLM/CosyVoice/HEAD/runtime/triton_trtllm/model_repo/audio_tokenizer/1/model.py
Generate helpful docstrings for debugging
# Copyright 2025, NVIDIA CORPORATION & AFFILIATES. All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # * Redistributions of source code must retain the above copyright # notice, this list of con...
--- +++ @@ -38,8 +38,18 @@ class TritonPythonModel: + """Triton Python model for audio tokenization. + + This model takes reference audio input and extracts semantic tokens + using s3tokenizer. + """ def initialize(self, args): + """Initialize the model. + + Args: + args:...
https://raw.githubusercontent.com/FunAudioLLM/CosyVoice/HEAD/runtime/triton_trtllm/model_repo/speaker_embedding/1/model.py
Generate consistent documentation across files
import argparse import json import os import time import asyncio import torch import torchaudio import s3tokenizer import soundfile as sf import requests import httpx from transformers import AutoTokenizer from datasets import load_dataset from torch.utils.data import DataLoader from functools import partial from tqdm...
--- +++ @@ -1,3 +1,14 @@+""" Example Usage + CUDA_VISIBLE_DEVICES=0 \ + python3 infer_cosyvoice3_token2wav.py \ + --output-dir $output_dir \ + --llm-model-name-or-path $huggingface_model_local_dir \ + --token2wav-path $token2wav_model_dir \ + --backend $backend \ + ...
https://raw.githubusercontent.com/FunAudioLLM/CosyVoice/HEAD/runtime/triton_trtllm/infer_cosyvoice3.py
Add inline docstrings for readability
import torch import torchaudio import torchaudio.compliance.kaldi as kaldi import onnxruntime import s3tokenizer import os import logging import argparse import queue import time import numpy as np from functools import partial from hyperpyyaml import load_hyperpyyaml from matcha.utils.audio import mel_spectrogram as m...
--- +++ @@ -1,3 +1,7 @@+""" Example Usage + CUDA_VISIBLE_DEVICES=0 \ + python3 token2wav_cosyvoice3.py --enable-trt || exit 1 +""" import torch import torchaudio import torchaudio.compliance.kaldi as kaldi @@ -300,6 +304,7 @@ def forward_stream(self, generated_speech_tokens, prompt_speech_tokens, ...
https://raw.githubusercontent.com/FunAudioLLM/CosyVoice/HEAD/runtime/triton_trtllm/token2wav_cosyvoice3.py
Add docstrings to incomplete code
# Copyright 2025, NVIDIA CORPORATION & AFFILIATES. All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # * Redistributions of source code must retain the above copyright # notice, this list of con...
--- +++ @@ -161,8 +161,18 @@ class TritonPythonModel: + """Triton Python model for vocoder. + + This model takes global and semantic tokens as input and generates audio waveforms + using the BiCodec vocoder. + """ def initialize(self, args): + """Initialize the model. + + Args: + ...
https://raw.githubusercontent.com/FunAudioLLM/CosyVoice/HEAD/runtime/triton_trtllm/model_repo/token2wav/1/model.py
Document functions with clear intent
# Copyright 2025, NVIDIA CORPORATION & AFFILIATES. All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # * Redistributions of source code must retain the above copyright # notice, this list of con...
--- +++ @@ -50,6 +50,9 @@ def parse_speech_token_string(response_text: str) -> List[int]: + """ + Parses a string of speech tokens (e.g., "<|s_123|><|s_456|>") into a list of integer IDs. + """ speech_tokens = response_text.strip().split('><') if len(speech_tokens) > 1: # Add back the mi...
https://raw.githubusercontent.com/FunAudioLLM/CosyVoice/HEAD/runtime/triton_trtllm/model_repo/cosyvoice2_dit/1/model.py
Add well-formatted docstrings
# Copyright 2025, NVIDIA CORPORATION & AFFILIATES. All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # * Redistributions of source code must retain the above copyright # notice, this list of con...
--- +++ @@ -46,8 +46,18 @@ class TritonPythonModel: + """Triton Python model for Spark TTS. + + This model orchestrates the end-to-end TTS pipeline by coordinating + between audio tokenizer, LLM, and vocoder components. + """ def initialize(self, args): + """Initialize the model. + + ...
https://raw.githubusercontent.com/FunAudioLLM/CosyVoice/HEAD/runtime/triton_trtllm/model_repo/cosyvoice2/1/model.py
Write docstrings for utility functions
# Copyright 2025, NVIDIA CORPORATION & AFFILIATES. All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # * Redistributions of source code must retain the above copyright # notice, this list of con...
--- +++ @@ -54,6 +54,10 @@ def get_spk_id_from_prompt_audio(tensor: torch.Tensor) -> str: + """ + Generates a unique ID for a torch.Tensor. + Tensors with the same elements and properties will have the same ID. + """ # Convert tensor to a byte string tensor_bytes = tensor.numpy().tobytes() @...
https://raw.githubusercontent.com/FunAudioLLM/CosyVoice/HEAD/runtime/triton_trtllm/model_repo/token2wav_dit/1/model.py
Auto-generate documentation strings for this file
import json import re import time import asyncio import numpy as np import torch from torch.utils.dlpack import to_dlpack import triton_python_backend_utils as pb_utils import httpx import torchaudio from functools import partial from matcha.utils.audio import mel_spectrogram as matcha_mel_spectrogram torch.set_num...
--- +++ @@ -23,6 +23,7 @@ def parse_speech_token_string(response_text): + """Parse speech tokens from string like '<|s_123|><|s_456|>' into list of int IDs.""" speech_tokens = response_text.strip().split('><') if len(speech_tokens) > 1: speech_tokens = ['<' + t if not t.startswith('<') else t ...
https://raw.githubusercontent.com/FunAudioLLM/CosyVoice/HEAD/runtime/triton_trtllm/model_repo_cosyvoice3/cosyvoice3/1/model.py
Document this module using docstrings
# Copyright 2025, NVIDIA CORPORATION & AFFILIATES. All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # * Redistributions of source code must retain the above copyright # notice, this list of con...
--- +++ @@ -37,8 +37,18 @@ class TritonPythonModel: + """Triton Python model for audio tokenization. + + This model takes reference audio input and extracts semantic tokens + using s3tokenizer. + """ def initialize(self, args): + """Initialize the model. + + Args: + args:...
https://raw.githubusercontent.com/FunAudioLLM/CosyVoice/HEAD/runtime/triton_trtllm/model_repo_cosyvoice3/audio_tokenizer/1/model.py
Add docstrings following best practices
# SPDX-FileCopyrightText: Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved. # SPDX-License-Identifier: Apache-2.0 # # 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://ww...
--- +++ @@ -12,6 +12,10 @@ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. +""" Example Usage + CUDA_VISIBLE_DEVICES=0 \ + python3 token2wav.py --enable-trt || exit 1 +""" impor...
https://raw.githubusercontent.com/FunAudioLLM/CosyVoice/HEAD/runtime/triton_trtllm/model_repo/token2wav_dit/1/token2wav_dit.py
Add docstrings following best practices
# Copyright 2025, NVIDIA CORPORATION & AFFILIATES. All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # * Redistributions of source code must retain the above copyright # notice, this list of con...
--- +++ @@ -38,8 +38,18 @@ class TritonPythonModel: + """Triton Python model for audio tokenization. + + This model takes reference audio input and extracts semantic tokens + using s3tokenizer. + """ def initialize(self, args): + """Initialize the model. + + Args: + args:...
https://raw.githubusercontent.com/FunAudioLLM/CosyVoice/HEAD/runtime/triton_trtllm/model_repo_cosyvoice3/speaker_embedding/1/model.py
Add professional docstrings to my codebase
#!/usr/bin/env python3 # Copyright 2025 CosyVoice3 TRT-LLM Integration # # 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 b...
--- +++ @@ -12,6 +12,24 @@ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. +""" +Convert CosyVoice3 LLM to HuggingFace format with merged embeddings. + +This script: +1. Loads CosyVoice3 m...
https://raw.githubusercontent.com/FunAudioLLM/CosyVoice/HEAD/runtime/triton_trtllm/scripts/convert_cosyvoice3_to_hf.py
Provide clean and structured docstrings
# SPDX-FileCopyrightText: Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved. # SPDX-License-Identifier: Apache-2.0 # # 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://ww...
--- +++ @@ -12,6 +12,17 @@ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. +""" Example Usage + CUDA_VISIBLE_DEVICES=0 \ + python3 offline_inference.py \ + --output-di...
https://raw.githubusercontent.com/FunAudioLLM/CosyVoice/HEAD/runtime/triton_trtllm/offline_inference.py
Generate docstrings for exported functions
# Copyright 2024 Bytedance Ltd. and/or its affiliates # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law ...
--- +++ @@ -11,6 +11,9 @@ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. +"""Diagnose script for checking OS/hardware/python/pip/verl/network. +The output of this script can be a very goo...
https://raw.githubusercontent.com/verl-project/verl/HEAD/scripts/diagnose.py
Add structured docstrings to improve clarity
# Copyright 2024 Bytedance Ltd. and/or its affiliates # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law ...
--- +++ @@ -47,6 +47,9 @@ class NixlAgent: + """This is a wrapper class for nixl_agent, the main purpose is to use ZeroMQ instead of + `nixl_agent.send_notif` to send bucket tensor metadata. + """ def __init__(self): self.agent_name = str(uuid.uuid4()) @@ -132,6 +135,17 @@ class Readabl...
https://raw.githubusercontent.com/verl-project/verl/HEAD/verl/checkpoint_engine/nixl_checkpoint_engine.py
Fill in missing docstrings in my code
# Copyright 2024 Bytedance Ltd. and/or its affiliates # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law ...
--- +++ @@ -41,6 +41,16 @@ class BroadcastOperation: + """Async broadcast operation with NCCL in separate thread. + + Args: + rank (int): The rank of the current process. + group_name (str): The name of the NCCL process group. + bucket (cp.ndarray | torch.Tensor): The tensor to broadcast....
https://raw.githubusercontent.com/verl-project/verl/HEAD/verl/checkpoint_engine/nccl_checkpoint_engine.py
Add inline docstrings for readability
# Copyright 2025 Meituan Ltd. and/or its affiliates # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or...
--- +++ @@ -25,6 +25,9 @@ @ray.remote(num_cpus=2, max_concurrency=20) class MessageQueue: + """ + Simplified Ray-based asynchronous message queue for communication between Rollouter and Trainer + """ def __init__(self, config: DictConfig, max_queue_size: int = 1000): self.config = config @@ ...
https://raw.githubusercontent.com/verl-project/verl/HEAD/verl/experimental/fully_async_policy/message_queue.py
Write documentation strings for class attributes
# Copyright 2025 Meituan Ltd. and/or its affiliates # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or...
--- +++ @@ -26,6 +26,7 @@ @dataclass class RolloutSample: + """Enhanced rollout sample containing both original batch info and AgentLoopOutput""" # Original batch information full_batch: Any @@ -40,12 +41,20 @@ @dataclass class ValidateMetrics: + """Metrics for validation""" timing_raw: d...
https://raw.githubusercontent.com/verl-project/verl/HEAD/verl/experimental/fully_async_policy/detach_utils.py
Add docstrings explaining edge cases
# Copyright 2025 Bytedance Ltd. and/or its affiliates # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law ...
--- +++ @@ -115,6 +115,20 @@ x_t: torch.Tensor, timestep: torch.Tensor, ) -> Tensor: + """Full forward pass for one diffusion denoising step. + + Args: + images: List of image tensors, each shaped (B, C, H, W) after batching. + img_masks: List of boolean masks c...
https://raw.githubusercontent.com/verl-project/verl/HEAD/verl/experimental/vla/models/pi0_torch/modeling_pi0_torch.py
Provide docstrings following PEP 257
# Copyright 2024 Bytedance Ltd. and/or its affiliates # Copyright 2023-2024 SGLang Team # Copyright 2025 ModelBest Inc. and/or its affiliates # # 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 #...
--- +++ @@ -13,6 +13,10 @@ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. +""" +PPO Trainer with Ray-based single controller. +This trainer supports model-agonistic model initialization w...
https://raw.githubusercontent.com/verl-project/verl/HEAD/verl/experimental/vla/rob_ray_trainer.py
Write docstrings that follow conventions
# Copyright 2025 Bytedance Ltd. and/or its affiliates # Copyright 2025 Giga Team. and/or its affiliates # # 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/...
--- +++ @@ -109,6 +109,17 @@ output_hidden_states: Optional[bool] = None, interpolate_pos_encoding: Optional[bool] = False, ) -> BaseModelOutputWithPooling: + """Forward pass of the SigLIP vision encoder. + + Args: + pixel_values: Image tensor expected by SigLIP (B, C, H, ...
https://raw.githubusercontent.com/verl-project/verl/HEAD/verl/experimental/vla/models/pi0_torch/model/paligemma_with_expert.py
Add docstrings to my Python code
# Copyright 2024 Bytedance Ltd. and/or its affiliates # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law ...
--- +++ @@ -25,6 +25,9 @@ @ray.remote(num_cpus=1) class RewardComputeWorker: + """ + WARNING: This class cannot have async methods. + """ def __init__(self, compute_score_fn): # since the reward function may not be pickleable, we need to init it in the worker @@ -36,6 +39,13 @@ @register("...
https://raw.githubusercontent.com/verl-project/verl/HEAD/verl/experimental/reward_loop/reward_manager/remote.py
Document helper functions with docstrings
# Copyright 2025 Bytedance Ltd. and/or its affiliates # # 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 # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law...
--- +++ @@ -15,6 +15,12 @@ # from https://github.com/PRIME-RL/SimpleVLA-RL/blob/main/verl/utils/vla_utils/openvla_oft/ # form https://huggingface.co/Haozhan72/Openvla-oft-SFT-libero10-trajall/blob/main/ +""" +processing_prismatic.py + +HuggingFace-style preprocessor definitions for Prismatic VLMs, inheriting from `P...
https://raw.githubusercontent.com/verl-project/verl/HEAD/verl/experimental/vla/models/openvla_oft/processing_prismatic.py
Include argument descriptions in docstrings
# Copyright 2024 Bytedance Ltd. and/or its affiliates # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law ...
--- +++ @@ -36,6 +36,9 @@ def migrate_legacy_reward_impl(config): + """ + Migrate the legacy reward model implementation to the new one. + """ # 1. reward workers migration # config.reward_model.num_workers -> config.reward.num_workers if config.reward_model.num_workers is not None: @@ -87,8...
https://raw.githubusercontent.com/verl-project/verl/HEAD/verl/experimental/reward_loop/reward_loop.py
Add docstrings to incomplete code
# Copyright 2025 Bytedance Ltd. and/or its affiliates # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law ...
--- +++ @@ -50,6 +50,8 @@ class AgentData: + """Encapsulates all state variables for the agent loop. AgentData is passed to tool calling in case that + tool may need to access full history state. User can store any tool session data in `extra_fields`.""" def __init__( self, @@ -199,6 +201,7 @@...
https://raw.githubusercontent.com/verl-project/verl/HEAD/verl/experimental/agent_loop/tool_agent_loop.py
Write docstrings for algorithm functions
# Copyright 2024 Bytedance Ltd. and/or its affiliates # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law ...
--- +++ @@ -11,6 +11,9 @@ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. +""" +The main entry point to run the PPO algorithm +""" import asyncio import contextlib @@ -47,6 +50,10 @@ ...
https://raw.githubusercontent.com/verl-project/verl/HEAD/verl/experimental/vla/fsdp_workers.py
Add professional docstrings to my codebase
# Copyright 2025 Bytedance Ltd. and/or its affiliates # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law o...
--- +++ @@ -20,28 +20,67 @@ # BaseConfig class inherits from collections.abc.Mapping, which means it can act like a dictionary @dataclass class BaseConfig(collections.abc.Mapping): + """The BaseConfig provides dict-like interface for a dataclass config. + + By default all fields in the config is not mutable, un...
https://raw.githubusercontent.com/verl-project/verl/HEAD/verl/base_config.py
Write documentation strings for class attributes
# Copyright 2024 Bytedance Ltd. and/or its affiliates # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law ...
--- +++ @@ -43,6 +43,16 @@ class BroadcastOperation: + """Async broadcast operation with HCCL in separate thread. + + Args: + rank (int): The rank of the current process. + group_name (str): The name of the HCCL process group. + bucket (torch.Tensor): The tensor to broadcast. + met...
https://raw.githubusercontent.com/verl-project/verl/HEAD/verl/checkpoint_engine/hccl_checkpoint_engine.py
Provide clean and structured docstrings
# Copyright 2025 Bytedance Ltd. and/or its affiliates # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law ...
--- +++ @@ -28,8 +28,18 @@ class EnvLoop: + """An env loop manages interactions between models and vectorized environments. It's designed for computationally + intensive environments, such as robotics simulators.""" def __init__(self, env_wg: RayWorkerGroup, rollout_wg: RayWorkerGroup, config: DictConf...
https://raw.githubusercontent.com/verl-project/verl/HEAD/verl/experimental/vla/env_loop.py
Help me add docstrings to my project
# Copyright 2025 Meituan Ltd. and/or its affiliates # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or...
--- +++ @@ -41,6 +41,11 @@ @ray.remote(num_cpus=10, max_concurrency=100) class FullyAsyncRollouter(SeparateRayPPOTrainer): + """ + Asynchronous sample generator, responsible for continuously generating training samples + and putting them into MessageQueue + Based on the mature implementation improvements...
https://raw.githubusercontent.com/verl-project/verl/HEAD/verl/experimental/fully_async_policy/fully_async_rollouter.py