instruction
stringclasses
100 values
code
stringlengths
78
193k
response
stringlengths
259
170k
file
stringlengths
59
203
Write Python docstrings for this snippet
#!/usr/bin/env python # -*- coding: utf-8; py-indent-offset:4 -*- ############################################################################### # # Copyright (C) 2015-2023 Daniel Rodriguez # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License a...
--- +++ @@ -25,6 +25,43 @@ class PivotPoint(Indicator): + ''' + Defines a level of significance by taking into account the average of price + bar components of the past period of a larger timeframe. For example when + operating with days, the values are taking from the already "past" month + fixed pr...
https://raw.githubusercontent.com/mementum/backtrader/HEAD/backtrader/indicators/pivotpoint.py
Write clean docstrings for readability
#!/usr/bin/env python # -*- coding: utf-8; py-indent-offset:4 -*- ############################################################################### # # Copyright (C) 2015-2023 Daniel Rodriguez # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License a...
--- +++ @@ -161,6 +161,7 @@ class MetaSingleton(MetaParams): + '''Metaclass to make a metaclassed class a singleton''' def __init__(cls, name, bases, dct): super(MetaSingleton, cls).__init__(name, bases, dct) cls._singleton = None @@ -174,6 +175,19 @@ class OandaStore(with_metaclass(Me...
https://raw.githubusercontent.com/mementum/backtrader/HEAD/backtrader/stores/oandastore.py
Add well-formatted docstrings
#!/usr/bin/env python # -*- coding: utf-8; py-indent-offset:4 -*- ############################################################################### # # Copyright (C) 2015-2023 Daniel Rodriguez # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License a...
--- +++ @@ -25,6 +25,17 @@ class FixedSize(bt.Sizer): + ''' + This sizer simply returns a fixed size for any operation. + Size can be controlled by number of tranches that a system + wishes to use to scale into trades by specifying the ``tranches`` + parameter. + + + Params: + - ``stake`` (de...
https://raw.githubusercontent.com/mementum/backtrader/HEAD/backtrader/sizers/fixedsize.py
Generate consistent docstrings
#!/usr/bin/env python # -*- coding: utf-8; py-indent-offset:4 -*- ############################################################################### # # Copyright (C) 2015-2023 Daniel Rodriguez # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License a...
--- +++ @@ -39,11 +39,36 @@ class PriceOscillator(_PriceOscBase): + ''' + Shows the difference between a short and long exponential moving + averages expressed in points. + + Formula: + - po = ema(short) - ema(long) + + See: + - http://www.metastock.com/Customer/Resources/TAAZ/?c=3&p=94 + ...
https://raw.githubusercontent.com/mementum/backtrader/HEAD/backtrader/indicators/priceoscillator.py
Add docstrings for better understanding
#!/usr/bin/env python # -*- coding: utf-8; py-indent-offset:4 -*- ############################################################################### # # Copyright (C) 2015-2023 Daniel Rodriguez # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License a...
--- +++ @@ -27,6 +27,23 @@ class Sizer(with_metaclass(MetaParams, object)): + '''This is the base class for *Sizers*. Any *sizer* should subclass this + and override the ``_getsizing`` method + + Member Attribs: + + - ``strategy``: will be set by the strategy in which the sizer is working + + G...
https://raw.githubusercontent.com/mementum/backtrader/HEAD/backtrader/sizer.py
Generate consistent docstrings
#!/usr/bin/env python # -*- coding: utf-8; py-indent-offset:4 -*- ############################################################################### # # Copyright (C) 2015-2023 Daniel Rodriguez # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License a...
--- +++ @@ -41,6 +41,7 @@ self.suffix = self.Suffixes[magnitude] def __call__(self, y, pos=0): + '''Return the label for time x at position pos''' if y > self.volmax * 1.20: return '' @@ -56,6 +57,7 @@ self.fmt = fmt def __call__(self, x, pos=0): + '''...
https://raw.githubusercontent.com/mementum/backtrader/HEAD/backtrader/plot/formatters.py
Add structured docstrings to improve clarity
#!/usr/bin389/env python # -*- coding: utf-8; py-indent-offset:4 -*- ############################################################################### # # Copyright (C) 2015-2023 Daniel Rodriguez # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public Licens...
--- +++ @@ -55,6 +55,9 @@ return super(MetaStrategy, meta).__new__(meta, name, bases, dct) def __init__(cls, name, bases, dct): + ''' + Class has already been created ... register subclasses + ''' # Initialize the class super(MetaStrategy, cls).__init__(name, bases,...
https://raw.githubusercontent.com/mementum/backtrader/HEAD/backtrader/strategy.py
Generate descriptive docstrings automatically
#!/usr/bin/env python # -*- coding: utf-8; py-indent-offset:4 -*- ############################################################################### # # Copyright (C) 2015-2023 Daniel Rodriguez # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License a...
--- +++ @@ -28,6 +28,19 @@ class OscillatorMixIn(Indicator): + ''' + MixIn class to create a subclass with another indicator. The main line of + that indicator will be substracted from the other base class main line + creating an oscillator + + The usage is: + + - Class XXXOscillator(XXX, Oscill...
https://raw.githubusercontent.com/mementum/backtrader/HEAD/backtrader/indicators/oscillator.py
Replace inline comments with docstrings
#!/usr/bin/env python # -*- coding: utf-8; py-indent-offset:4 -*- ############################################################################### # # Copyright (C) 2015-2023 Daniel Rodriguez # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License a...
--- +++ @@ -26,6 +26,17 @@ class Position(object): + ''' + Keeps and updates the size and price of a position. The object has no + relationship to any asset. It only keeps size and price. + + Member Attributes: + - size (int): current size of the position + - price (float): current price of th...
https://raw.githubusercontent.com/mementum/backtrader/HEAD/backtrader/position.py
Write Python docstrings for this snippet
#!/usr/bin/env python # -*- coding: utf-8; py-indent-offset:4 -*- ############################################################################### # # Copyright (C) 2015-2023 Daniel Rodriguez # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License a...
--- +++ @@ -52,6 +52,11 @@ class RTVolume(object): + '''Parses a tickString tickType 48 (RTVolume) event from the IB API into its + constituent fields + + Supports using a "price" to simulate an RTVolume from a tickPrice event + ''' _fields = [ ('price', float), ('size', int), @@ ...
https://raw.githubusercontent.com/mementum/backtrader/HEAD/backtrader/stores/ibstore.py
Add docstrings for better understanding
#!/usr/bin/env python # -*- coding: utf-8; py-indent-offset:4 -*- ############################################################################### # # Copyright (C) 2015-2023 Daniel Rodriguez # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License a...
--- +++ @@ -27,6 +27,11 @@ class PercentSizer(bt.Sizer): + '''This sizer return percents of available cash + + Params: + - ``percents`` (default: ``20``) + ''' params = ( ('percents', 20), @@ -50,12 +55,23 @@ class AllInSizer(PercentSizer): + '''This sizer return all available c...
https://raw.githubusercontent.com/mementum/backtrader/HEAD/backtrader/sizers/percents_sizer.py
Annotate my code with docstrings
#!/usr/bin/env python # -*- coding: utf-8; py-indent-offset:4 -*- ############################################################################### # # Copyright (C) 2015-2023 Daniel Rodriguez # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License a...
--- +++ @@ -240,6 +240,12 @@ data.num2date(self.bar.datetime).year) def _gettmpoint(self, tm): + '''Returns the point of time intraday for a given time according to the + timeframe + + - Ex 1: 00:05:00 in minutes -> point = 5 + - Ex 2: 00:05:20 in seconds -> point ...
https://raw.githubusercontent.com/mementum/backtrader/HEAD/backtrader/resamplerfilter.py
Document this module using docstrings
#!/usr/bin/env python # -*- coding: utf-8; py-indent-offset:4 -*- ############################################################################### # # Copyright (C) 2015-2023 Daniel Rodriguez # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License a...
--- +++ @@ -26,6 +26,20 @@ class WilliamsR(Indicator): + ''' + Developed by Larry Williams to show the relation of closing prices to + the highest-lowest range of a given period. + + Known as Williams %R (but % is not allowed in Python identifiers) + + Formula: + - num = highest_period - close +...
https://raw.githubusercontent.com/mementum/backtrader/HEAD/backtrader/indicators/williams.py
Document classes and their methods
#!/usr/bin/env python # -*- coding: utf-8; py-indent-offset:4 -*- ############################################################################### # # Copyright (C) 2015-2023 Daniel Rodriguez # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License a...
--- +++ @@ -65,6 +65,9 @@ super(RRuleLocator, self).__init__(o, tz) def datalim_to_dt(self): + """ + Convert axis data interval to datetime objects. + """ dmin, dmax = self.axis.get_data_interval() if dmin > dmax: dmin, dmax = dmax, dmin @@ -73,6 +76,9 ...
https://raw.githubusercontent.com/mementum/backtrader/HEAD/backtrader/plot/locator.py
Add inline docstrings for readability
#!/usr/bin/env python # -*- coding: utf-8; py-indent-offset:4 -*- ############################################################################### # # Copyright (C) 2015-2023 Daniel Rodriguez # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License a...
--- +++ @@ -30,6 +30,12 @@ class OLS_Slope_InterceptN(PeriodN): + ''' + Calculates a linear regression using ``statsmodel.OLS`` (Ordinary least + squares) of data1 on data0 + + Uses ``pandas`` and ``statsmodels`` + ''' _mindatas = 2 # ensure at least 2 data feeds are passed packages = ( ...
https://raw.githubusercontent.com/mementum/backtrader/HEAD/backtrader/indicators/ols.py
Create docstrings for API functions
#!/usr/bin/env python # -*- coding: utf-8; py-indent-offset:4 -*- ############################################################################### # # Copyright (C) 2015-2023 Daniel Rodriguez # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License a...
--- +++ @@ -28,6 +28,14 @@ def tag_box_style(x0, y0, width, height, mutation_size, mutation_aspect=1): + """ + Given the location and size of the box, return the path of + the box around it. + + - *x0*, *y0*, *width*, *height* : location and size of the box + - *mutation_size* : a reference scale f...
https://raw.githubusercontent.com/mementum/backtrader/HEAD/backtrader/plot/utils.py
Add professional docstrings to my codebase
#!/usr/bin/env python # -*- coding: utf-8; py-indent-offset:4 -*- ############################################################################### # # Copyright (C) 2015-2023 Daniel Rodriguez # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License a...
--- +++ @@ -29,9 +29,35 @@ class TradeHistory(AutoOrderedDict): + '''Represents the status and update event for each update a Trade has + + This object is a dictionary which allows '.' notation + + Attributes: + - ``status`` (``dict`` with '.' notation): Holds the resulting status of + an updat...
https://raw.githubusercontent.com/mementum/backtrader/HEAD/backtrader/trade.py
Write docstrings for data processing functions
#!/usr/bin/env python # -*- coding: utf-8; py-indent-offset:4 -*- ############################################################################### # # Copyright (C) 2015-2023 Daniel Rodriguez # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License a...
--- +++ @@ -26,6 +26,19 @@ class UpDay(Indicator): + ''' + Defined by J. Welles Wilder, Jr. in 1978 in his book *"New Concepts in + Technical Trading Systems"* for the RSI + + Records days which have been "up", i.e.: the close price has been + higher than the day before. + + Formula: + - upda...
https://raw.githubusercontent.com/mementum/backtrader/HEAD/backtrader/indicators/rsi.py
Add standardized docstrings across the file
# LICENSE AGREEMENT FOR MATPLOTLIB 1.2.0 # -------------------------------------- # # 1. This LICENSE AGREEMENT is between John D. Hunter ("JDH"), and the # Individual or Organization ("Licensee") accessing and otherwise using # matplotlib software in source or binary form and its associated # documentation. # # 2. Sub...
--- +++ @@ -63,14 +63,21 @@ from ..utils.py3 import zip class Widget(object): + """ + Abstract base class for GUI neutral widgets + """ drawon = True eventson = True _active = True def set_active(self, active): + """Set whether the widget is active. + """ self._a...
https://raw.githubusercontent.com/mementum/backtrader/HEAD/backtrader/plot/multicursor.py
Document classes and their methods
#!/usr/bin/env python # -*- coding: utf-8; py-indent-offset:4 -*- ############################################################################### # # Copyright (C) 2015-2023 Daniel Rodriguez # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License a...
--- +++ @@ -46,34 +46,95 @@ class TradingCalendarBase(with_metaclass(MetaParams, object)): def _nextday(self, day): + ''' + Returns the next trading day (datetime/date instance) after ``day`` + (datetime/date instance) and the isocalendar components + + The return value is a tuple wit...
https://raw.githubusercontent.com/mementum/backtrader/HEAD/backtrader/tradingcal.py
Provide docstrings following PEP 257
#!/usr/bin/env python # -*- coding: utf-8; py-indent-offset:4 -*- ############################################################################### # # Copyright (C) 2015-2023 Daniel Rodriguez # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License a...
--- +++ @@ -25,6 +25,25 @@ class Trix(Indicator): + ''' + Defined by Jack Hutson in the 80s and shows the Rate of Change (%) or slope + of a triple exponentially smoothed moving average + + Formula: + - ema1 = EMA(data, period) + - ema2 = EMA(ema1, period) + - ema3 = EMA(ema2, period) + ...
https://raw.githubusercontent.com/mementum/backtrader/HEAD/backtrader/indicators/trix.py
Add inline docstrings for readability
#!/usr/bin/env python # -*- coding: utf-8; py-indent-offset:4 -*- ############################################################################### # # Copyright (C) 2015-2023 Daniel Rodriguez # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License a...
--- +++ @@ -25,6 +25,17 @@ class Momentum(Indicator): + ''' + Measures the change in price by calculating the difference between the + current price and the price from a given period ago + + + Formula: + - momentum = data - data_period + + See: + - http://en.wikipedia.org/wiki/Momentum_(tec...
https://raw.githubusercontent.com/mementum/backtrader/HEAD/backtrader/indicators/momentum.py
Can you add docstrings to this Python file?
#!/usr/bin/env python # -*- coding: utf-8; py-indent-offset:4 -*- ############################################################################### # # Copyright (C) 2015-2023 Daniel Rodriguez # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License a...
--- +++ @@ -33,6 +33,31 @@ class OrderExecutionBit(object): + ''' + Intended to hold information about order execution. A "bit" does not + determine if the order has been fully/partially executed, it just holds + information. + + Member Attributes: + + - dt: datetime (float) execution time + ...
https://raw.githubusercontent.com/mementum/backtrader/HEAD/backtrader/order.py
Add docstrings following best practices
#!/usr/bin/env python # -*- coding: utf-8; py-indent-offset:4 -*- ############################################################################### # # Copyright (C) 2015-2023 Daniel Rodriguez # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License a...
--- +++ @@ -56,6 +56,28 @@ class StochasticFast(_StochasticBase): + ''' + By Dr. George Lane in the 50s. It compares a closing price to the price + range and tries to show convergence if the closing prices are close to the + extremes + + - It will go up if closing prices are close to the highs + ...
https://raw.githubusercontent.com/mementum/backtrader/HEAD/backtrader/indicators/stochastic.py
Generate documentation strings for clarity
#!/usr/bin/env python # -*- coding: utf-8; py-indent-offset:4 -*- ############################################################################### # # Copyright (C) 2015-2023 Daniel Rodriguez # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License a...
--- +++ @@ -85,6 +85,7 @@ # A UTC class, same as the one in the Python Docs class _UTC(datetime.tzinfo): + """UTC""" def utcoffset(self, dt): return ZERO @@ -148,6 +149,18 @@ def num2date(x, tz=None, naive=True): # Same as matplotlib except if tz is None a naive datetime object # will be...
https://raw.githubusercontent.com/mementum/backtrader/HEAD/backtrader/utils/dateintern.py
Create docstrings for reusable components
#!/usr/bin/env python3 # -*- coding: utf-8; py-indent-offset:4 -*- import sys import os import io import socket import logging import numpy as np import pandas as pd import datetime as dt import argparse from influxdb import DataFrameClient as dfclient from influxdb.exceptions import InfluxDBClientError class IQFeed...
--- +++ @@ -57,9 +57,11 @@ sys.exit(-1) def _send_cmd(self, cmd: str): + """Encode IQFeed API messages.""" self._sock.sendall(cmd.encode(encoding='latin-1', errors='strict')) def iq_query(self, message: str): + """Send data query to IQFeed API.""" end_msg = '!EN...
https://raw.githubusercontent.com/mementum/backtrader/HEAD/contrib/utils/iqfeed-to-influxdb.py
Add docstrings including usage examples
#!/usr/bin/env python # -*- coding: utf-8; py-indent-offset:4 -*- ############################################################################### # # Copyright (C) 2015-2023 Daniel Rodriguez # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License a...
--- +++ @@ -62,9 +62,26 @@ class SessionEndFiller(with_metaclass(bt.metabase.MetaParams, object)): + '''This data filter simply adds the time given in param ``endtime`` to the + current data datetime + + It is intended for daily bars which come from sources with no time + indication and can be used to s...
https://raw.githubusercontent.com/mementum/backtrader/HEAD/samples/order-close/close-daily.py
Add inline docstrings for readability
#!/usr/bin/env python # -*- coding: utf-8; py-indent-offset:4 -*- ############################################################################### # # Copyright (C) 2015-2023 Daniel Rodriguez # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License a...
--- +++ @@ -29,6 +29,35 @@ class LogReturns(bt.Observer): + '''This observer stores the *log returns* of the strategy or a + + Params: + + - ``timeframe`` (default: ``None``) + If ``None`` then the complete return over the entire backtested period + will be reported + + Pass ``TimeFr...
https://raw.githubusercontent.com/mementum/backtrader/HEAD/backtrader/observers/logreturns.py
Document all endpoints with docstrings
#!/usr/bin/env python # -*- coding: utf-8; py-indent-offset:4 -*- ############################################################################### # # Copyright (C) 2015-2023 Daniel Rodriguez # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License a...
--- +++ @@ -29,6 +29,22 @@ class DayStepsCloseFilter(bt.with_metaclass(bt.MetaParams, object)): + ''' + Replays a bar in 2 steps: + + - In the 1st step the "Open-High-Low" could be evaluated to decide if to + act on the close (the close is still there ... should not be evaluated) + + - If a "...
https://raw.githubusercontent.com/mementum/backtrader/HEAD/samples/pinkfish-challenge/pinkfish-challenge.py
Replace inline comments with docstrings
#!/usr/bin/env python # -*- coding: utf-8; py-indent-offset:4 -*- ############################################################################### # # Copyright (C) 2015-2023 Daniel Rodriguez # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License a...
--- +++ @@ -54,6 +54,12 @@ def PumpEvents(timeout=-1, hevt=None, cb=None): + """This following code waits for 'timeout' seconds in the way + required for COM, internally doing the correct things depending + on the COM appartment of the current thread. It is possible to + terminate the message loop by p...
https://raw.githubusercontent.com/mementum/backtrader/HEAD/backtrader/stores/vcstore.py
Write docstrings that follow conventions
#!/usr/bin/env python # -*- coding: utf-8; py-indent-offset:4 -*- ############################################################################### # # Copyright (C) 2015-2023 Daniel Rodriguez # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License a...
--- +++ @@ -26,6 +26,21 @@ class DrawDown(Observer): + '''This observer keeps track of the current drawdown level (plotted) and + the maxdrawdown (not plotted) levels + + Params: + + - ``fund`` (default: ``None``) + + If ``None`` the actual mode of the broker (fundmode - True/False) will + ...
https://raw.githubusercontent.com/mementum/backtrader/HEAD/backtrader/observers/drawdown.py
Write docstrings for algorithm functions
#!/usr/bin/env python # -*- coding: utf-8; py-indent-offset:4 -*- ############################################################################### # # Copyright (C) 2015-2023 Daniel Rodriguez # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License a...
--- +++ @@ -25,6 +25,10 @@ class Cash(Observer): + '''This observer keeps track of the current amount of cash in the broker + + Params: None + ''' _stclock = True lines = ('cash',) @@ -36,6 +40,21 @@ class Value(Observer): + '''This observer keeps track of the current portfolio value in ...
https://raw.githubusercontent.com/mementum/backtrader/HEAD/backtrader/observers/broker.py
Add docstrings to my Python code
#!/usr/bin/env python # -*- coding: utf-8; py-indent-offset:4 -*- ############################################################################### # # Copyright (C) 2015-2023 Daniel Rodriguez # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License a...
--- +++ @@ -32,6 +32,11 @@ class FixedPerc(bt.Sizer): + '''This sizer simply returns a fixed size for any operation + + Params: + - ``perc`` (default: ``0.20``) Perc of cash to allocate for operation + ''' params = ( ('perc', 0.20), # perc of cash to use for operation @@ -47,6 +52,24 ...
https://raw.githubusercontent.com/mementum/backtrader/HEAD/samples/macd-settings/macd-settings.py
Replace inline comments with docstrings
#!/usr/bin/env python # -*- coding: utf-8; py-indent-offset:4 -*- ############################################################################### # # Copyright (C) 2015-2023 Daniel Rodriguez # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License a...
--- +++ @@ -28,6 +28,7 @@ class MetaSingleton(MetaParams): + '''Metaclass to make a metaclassed class a singleton''' def __init__(cls, name, bases, dct): super(MetaSingleton, cls).__init__(name, bases, dct) cls._singleton = None @@ -41,18 +42,21 @@ class Store(with_metaclass(MetaSingle...
https://raw.githubusercontent.com/mementum/backtrader/HEAD/backtrader/store.py
Add docstrings that explain purpose and usage
#!/usr/bin/env python # -*- coding: utf-8; py-indent-offset:4 -*- ############################################################################### # # Copyright (C) 2015-2023 Daniel Rodriguez # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License a...
--- +++ @@ -30,6 +30,16 @@ class TheStrategy(bt.Strategy): + ''' + This strategy is capable of: + + - Going Long with a Moving Average upwards CrossOver + + - Going Long again with a MACD upwards CrossOver + + - Closing the aforementioned longs with the corresponding downwards + crossove...
https://raw.githubusercontent.com/mementum/backtrader/HEAD/samples/multi-copy/multi-copy.py
Generate docstrings for this script
#!/usr/bin/env python # -*- coding: utf-8; py-indent-offset:4 -*- ############################################################################### # # Copyright (C) 2015-2023 Daniel Rodriguez # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License a...
--- +++ @@ -25,6 +25,7 @@ class WeekDaysFiller(object): + '''Bar Filler to add missing calendar days to trading days''' # kickstart value for date comparisons ONEDAY = datetime.timedelta(days=1) lastdt = datetime.date.max - ONEDAY @@ -34,6 +35,16 @@ self.voidbar = [float('Nan')] * data.siz...
https://raw.githubusercontent.com/mementum/backtrader/HEAD/samples/weekdays-filler/weekdaysfiller.py
Write docstrings that follow conventions
import numpy as np import pandas as pd from pyannote.audio import Pipeline from typing import Optional, Union, List, Tuple import torch from whisperx.audio import load_audio, SAMPLE_RATE from whisperx.schema import TranscriptionResult, AlignedTranscriptionResult, ProgressCallback from whisperx.log_utils import get_log...
--- +++ @@ -12,8 +12,20 @@ class IntervalTree: + """ + Simple interval tree for fast overlap queries using sorted array + binary search. + + Uses O(n) space and provides O(log n) query time instead of O(n) linear scan. + This achieves ~228x speedup for speaker assignment in long-form content. + """ ...
https://raw.githubusercontent.com/m-bain/whisperX/HEAD/whisperx/diarize.py
Write docstrings describing each step
import os import subprocess from functools import lru_cache from typing import Optional, Union import numpy as np import torch import torch.nn.functional as F from whisperx.utils import exact_div # hard-coded audio hyperparameters SAMPLE_RATE = 16000 N_FFT = 400 HOP_LENGTH = 160 CHUNK_LENGTH = 30 N_SAMPLES = CHUNK_L...
--- +++ @@ -23,6 +23,21 @@ def load_audio(file: str, sr: int = SAMPLE_RATE) -> np.ndarray: + """ + Open an audio file and read as mono waveform, resampling as necessary + + Parameters + ---------- + file: str + The audio file to open + + sr: int + The sample rate to resample the audi...
https://raw.githubusercontent.com/m-bain/whisperX/HEAD/whisperx/audio.py
Generate docstrings for each module
import os from typing import Callable, Text, Union from typing import Optional import numpy as np import torch from pyannote.audio import Model from pyannote.audio.core.io import AudioFile from pyannote.audio.pipelines import VoiceActivityDetection from pyannote.audio.pipelines.utils import PipelineModel from pyannote...
--- +++ @@ -49,6 +49,37 @@ return vad_pipeline class Binarize: + """Binarize detection scores using hysteresis thresholding, with min-cut operation + to ensure not segments are longer than max_duration. + + Parameters + ---------- + onset : float, optional + Onset threshold. Defaults to 0.5...
https://raw.githubusercontent.com/m-bain/whisperX/HEAD/whisperx/vads/pyannote.py
Write beginner-friendly docstrings
from dataclasses import dataclass from typing import Iterable, Optional, Union, List import numpy as np import pandas as pd import torch import torchaudio from transformers import Wav2Vec2ForCTC, Wav2Vec2Processor from whisperx.audio import SAMPLE_RATE, load_audio from whisperx.utils import interpolate_nans, PUNKT_LA...
--- +++ @@ -1,3 +1,7 @@+""" +Forced Alignment with Whisper +C. Max Bain +""" from dataclasses import dataclass from typing import Iterable, Optional, Union, List @@ -121,6 +125,9 @@ combined_progress: bool = False, progress_callback: ProgressCallback = None, ) -> AlignedTranscriptionResult: + """ + ...
https://raw.githubusercontent.com/m-bain/whisperX/HEAD/whisperx/alignment.py
Please document this code using docstrings
from typing import Callable, TypedDict, Optional, List, Tuple ProgressCallback = Optional[Callable[[float], None]] try: from typing import NotRequired except ImportError: from typing_extensions import NotRequired class SingleWordSegment(TypedDict): word: str start: float end: float score: fl...
--- +++ @@ -9,12 +9,18 @@ class SingleWordSegment(TypedDict): + """ + A single word of a speech. + """ word: str start: float end: float score: float class SingleCharSegment(TypedDict): + """ + A single char of a speech. + """ char: str start: float end: float...
https://raw.githubusercontent.com/m-bain/whisperX/HEAD/whisperx/schema.py
Write docstrings for backend logic
import logging import sys from typing import Optional _LOG_FORMAT = "%(asctime)s - %(name)s - %(levelname)s - %(message)s" _DATE_FORMAT = "%Y-%m-%d %H:%M:%S" def setup_logging( level: str = "info", log_file: Optional[str] = None, ) -> None: logger = logging.getLogger("whisperx") logger.handlers.clea...
--- +++ @@ -10,6 +10,13 @@ level: str = "info", log_file: Optional[str] = None, ) -> None: + """ + Configure logging for WhisperX. + + Args: + level: Logging level (debug, info, warning, error, critical). Default: info + log_file: Optional path to log file. If None, logs only to console...
https://raw.githubusercontent.com/m-bain/whisperX/HEAD/whisperx/log_utils.py
Add clean documentation to messy code
import importlib def _lazy_import(name): module = importlib.import_module(f"whisperx.{name}") return module def load_align_model(*args, **kwargs): alignment = _lazy_import("alignment") return alignment.load_align_model(*args, **kwargs) def align(*args, **kwargs): alignment = _lazy_import("alig...
--- +++ @@ -32,10 +32,26 @@ def setup_logging(*args, **kwargs): + """ + Configure logging for WhisperX. + + Args: + level: Logging level (debug, info, warning, error, critical). Default: warning + log_file: Optional path to log file. If None, logs only to console. + """ logging_module...
https://raw.githubusercontent.com/m-bain/whisperX/HEAD/whisperx/__init__.py
Add docstrings that explain purpose and usage
# This code is based on the revised code from fastchat based on tatsu-lab/stanford_alpaca. from dataclasses import dataclass, field import json import math import logging import os from typing import Dict, Optional, List import torch from torch.utils.data import Dataset from deepspeed import zero from deepspeed.runti...
--- +++ @@ -107,6 +107,7 @@ def safe_save_model_for_hf_trainer(trainer: transformers.Trainer, output_dir: str, bias="none"): + """Collects the state dict and dump to disk.""" # check if zero3 mode enabled if deepspeed.is_deepspeed_zero3_enabled(): state_dict = trainer.model_wrapped._zero3_cons...
https://raw.githubusercontent.com/QwenLM/Qwen/HEAD/finetune.py
Write proper docstrings for these functions
import json import os import re import sys import zlib from typing import Callable, Optional, TextIO LANGUAGES = { "en": "english", "zh": "chinese", "de": "german", "es": "spanish", "ru": "russian", "ko": "korean", "fr": "french", "ja": "japanese", "pt": "portuguese", "tr": "tur...
--- +++ @@ -392,6 +392,14 @@ class WriteTSV(ResultWriter): + """ + Write a transcript to a file in TSV (tab-separated values) format containing lines like: + <start time in integer milliseconds>\t<end time in integer milliseconds>\t<transcript text> + + Using integer milliseconds as start and end times ...
https://raw.githubusercontent.com/m-bain/whisperX/HEAD/whisperx/utils.py
Add detailed docstrings explaining each function
import os from typing import List, Optional, Union from dataclasses import replace import ctranslate2 import faster_whisper import numpy as np import torch from faster_whisper.tokenizer import Tokenizer from faster_whisper.transcribe import TranscriptionOptions, get_ctranslate2_storage from transformers import Pipelin...
--- +++ @@ -29,6 +29,10 @@ return numeral_symbol_tokens class WhisperModel(faster_whisper.WhisperModel): + ''' + FasterWhisperModel provides batched inference for faster-whisper. + Currently only works in non-timestamp mode and fixed prompt for all samples in batch. + ''' def generate_segment_...
https://raw.githubusercontent.com/m-bain/whisperX/HEAD/whisperx/asr.py
Document all endpoints with docstrings
import abc from dataclasses import dataclass from typing import Any from pydantic import BaseModel, TypeAdapter from typing_extensions import TypedDict, get_args, get_origin from .exceptions import ModelBehaviorError, UserError from .strict_schema import ensure_strict_json_schema from .tracing import SpanError from ....
--- +++ @@ -14,30 +14,48 @@ class AgentOutputSchemaBase(abc.ABC): + """An object that captures the JSON schema of the output, as well as validating/parsing JSON + produced by the LLM into the output type. + """ @abc.abstractmethod def is_plain_text(self) -> bool: + """Whether the output ...
https://raw.githubusercontent.com/openai/openai-agents-python/HEAD/src/agents/agent_output.py
Document functions with clear intent
from __future__ import annotations import asyncio import json import sqlite3 import threading from pathlib import Path from ..items import TResponseInputItem from .session import SessionABC from .session_settings import SessionSettings, resolve_session_limit class SQLiteSession(SessionABC): session_settings: S...
--- +++ @@ -12,6 +12,12 @@ class SQLiteSession(SessionABC): + """SQLite-based implementation of session storage. + + This implementation stores conversation history in a SQLite database. + By default, uses an in-memory database that is lost when the process ends. + For persistent storage, provide a file...
https://raw.githubusercontent.com/openai/openai-agents-python/HEAD/src/agents/memory/sqlite_session.py
Add docstrings including usage examples
import abc from typing import Literal Environment = Literal["mac", "windows", "ubuntu", "browser"] Button = Literal["left", "right", "wheel", "back", "forward"] class Computer(abc.ABC): @property def environment(self) -> Environment | None: return None @property def dimensions(self) -> tupl...
--- +++ @@ -6,13 +6,17 @@ class Computer(abc.ABC): + """A computer implemented with sync operations. The Computer interface abstracts the + operations needed to control a computer or browser.""" @property def environment(self) -> Environment | None: + """Return preview tool metadata when th...
https://raw.githubusercontent.com/openai/openai-agents-python/HEAD/src/agents/computer.py
Create documentation for each function signature
from __future__ import annotations from dataclasses import dataclass from datetime import datetime from ._util import calculate_audio_length_ms from .config import RealtimeAudioFormat @dataclass class ModelAudioState: initial_received_time: datetime audio_length_ms: float class ModelAudioTracker: def ...
--- +++ @@ -20,9 +20,11 @@ self._last_audio_item: tuple[str, int] | None = None def set_audio_format(self, format: RealtimeAudioFormat) -> None: + """Called when the model wants to set the audio format.""" self._format = format def on_audio_delta(self, item_id: str, item_content_in...
https://raw.githubusercontent.com/openai/openai-agents-python/HEAD/src/agents/realtime/_default_tracker.py
Help me comply with documentation standards
from __future__ import annotations from collections.abc import Iterable, Mapping from dataclasses import dataclass from typing import Any @dataclass(frozen=True) class MCPToolMetadata: description: str | None = None title: str | None = None def _get_mapping_or_attr(value: Any, key: str) -> Any: if isi...
--- +++ @@ -7,6 +7,7 @@ @dataclass(frozen=True) class MCPToolMetadata: + """Resolved display metadata for an MCP tool.""" description: str | None = None title: str | None = None @@ -25,6 +26,7 @@ def resolve_mcp_tool_title(tool: Any) -> str | None: + """Return the MCP display title, preferring ...
https://raw.githubusercontent.com/openai/openai-agents-python/HEAD/src/agents/_mcp_tool_metadata.py
Add docstrings for production code
from __future__ import annotations import abc import json import weakref from collections.abc import Mapping from dataclasses import dataclass, field from typing import TYPE_CHECKING, Any, Generic, Literal, TypeVar, Union, cast import pydantic from openai.types.responses import ( Response, ResponseComputerToo...
--- +++ @@ -113,6 +113,7 @@ return super().__getattribute__(name) def release_agent(self) -> None: + """Release the strong reference to the agent while keeping a weak reference.""" if "agent" not in self.__dict__: return agent = self.__dict__["agent"] @@ -140,6 +141,...
https://raw.githubusercontent.com/openai/openai-agents-python/HEAD/src/agents/items.py
Write docstrings for backend logic
from __future__ import annotations from collections.abc import AsyncIterator, Mapping from contextlib import asynccontextmanager from dataclasses import dataclass from typing import Any from .agent import Agent from .items import TResponseInputItem from .models.multi_provider import ( MultiProvider, MultiProv...
--- +++ @@ -21,6 +21,7 @@ @dataclass(frozen=True) class ResponsesWebSocketSession: + """Helper that pins runs to a shared OpenAI websocket-capable provider.""" provider: OpenAIProvider run_config: RunConfig @@ -41,6 +42,7 @@ return model_provider async def aclose(self) -> None: + ...
https://raw.githubusercontent.com/openai/openai-agents-python/HEAD/src/agents/responses_websocket_session.py
Write docstrings describing each step
from __future__ import annotations import asyncio import json import logging import threading from contextlib import closing from pathlib import Path from typing import Any, Union, cast from agents.result import RunResult from agents.usage import Usage from ..._tool_identity import is_reserved_synthetic_tool_namespa...
--- +++ @@ -18,6 +18,7 @@ class AdvancedSQLiteSession(SQLiteSession): + """Enhanced SQLite session with conversation branching and usage analytics.""" def __init__( self, @@ -29,6 +30,15 @@ session_settings: SessionSettings | None = None, **kwargs, ): + """Initialize ...
https://raw.githubusercontent.com/openai/openai-agents-python/HEAD/src/agents/extensions/memory/advanced_sqlite_session.py
Document all public functions with docstrings
from typing import Any, Generic, Optional from typing_extensions import TypeVar from .agent import Agent, AgentBase from .items import ModelResponse, TResponseInputItem from .run_context import AgentHookContext, RunContextWrapper, TContext from .tool import Tool TAgent = TypeVar("TAgent", bound=AgentBase, default=Ag...
--- +++ @@ -11,6 +11,9 @@ class RunHooksBase(Generic[TContext, TAgent]): + """A class that receives callbacks on various lifecycle events in an agent run. Subclass and + override the methods you need. + """ async def on_llm_start( self, @@ -19,6 +22,7 @@ system_prompt: Optional[str]...
https://raw.githubusercontent.com/openai/openai-agents-python/HEAD/src/agents/lifecycle.py
Insert docstrings into my code
from __future__ import annotations import asyncio import contextlib import warnings from typing import Union, cast from typing_extensions import Unpack from . import _debug from ._tool_identity import get_tool_trace_name_for_tool from .agent import Agent from .agent_tool_state import set_agent_tool_state_scope from ...
--- +++ @@ -136,11 +136,19 @@ def set_default_agent_runner(runner: AgentRunner | None) -> None: + """ + WARNING: this class is experimental and not part of the public API + It should not be used directly. + """ global DEFAULT_AGENT_RUNNER DEFAULT_AGENT_RUNNER = runner or AgentRunner() def...
https://raw.githubusercontent.com/openai/openai-agents-python/HEAD/src/agents/run.py
Document all endpoints with docstrings
from __future__ import annotations import re from collections.abc import Sequence from dataclasses import dataclass from typing import Callable, Literal ApplyDiffMode = Literal["default", "create"] @dataclass class Chunk: orig_index: int del_lines: list[str] ins_lines: list[str] @dataclass class Pars...
--- +++ @@ -1,3 +1,4 @@+"""Utility for applying V4A diffs against text inputs.""" from __future__ import annotations @@ -49,6 +50,11 @@ def apply_diff(input: str, diff: str, mode: ApplyDiffMode = "default") -> str: + """Apply a V4A diff to the provided text. + + This parser understands both the create-fi...
https://raw.githubusercontent.com/openai/openai-agents-python/HEAD/src/agents/apply_diff.py
Create docstrings for all classes and functions
from __future__ import annotations import abc import asyncio import copy import weakref from collections.abc import AsyncIterator from dataclasses import InitVar, dataclass, field from typing import TYPE_CHECKING, Any, Literal, TypeVar, cast from pydantic import GetCoreSchemaHandler from pydantic_core import core_sch...
--- +++ @@ -53,6 +53,7 @@ @dataclass(frozen=True) class AgentToolInvocation: + """Immutable metadata about a nested agent-tool invocation.""" tool_name: str """The nested tool name exposed to the model.""" @@ -76,6 +77,7 @@ previous_response_id: str | None = None, auto_previous_response_id: b...
https://raw.githubusercontent.com/openai/openai-agents-python/HEAD/src/agents/result.py
Create docstrings for reusable components
from __future__ import annotations import inspect from collections.abc import Awaitable from dataclasses import dataclass from typing import TYPE_CHECKING, Any, Callable, Generic, Union, overload from typing_extensions import TypeVar from .exceptions import UserError from .items import TResponseInputItem from .run_c...
--- +++ @@ -18,6 +18,7 @@ @dataclass class GuardrailFunctionOutput: + """The output of a guardrail function.""" output_info: Any """ @@ -33,6 +34,7 @@ @dataclass class InputGuardrailResult: + """The result of a guardrail run.""" guardrail: InputGuardrail[Any] """ @@ -45,6 +47,7 @@ ...
https://raw.githubusercontent.com/openai/openai-agents-python/HEAD/src/agents/guardrail.py
Add docstrings that explain purpose and usage
from __future__ import annotations import asyncio import copy import functools import inspect import json from collections.abc import Awaitable from dataclasses import dataclass from typing import TYPE_CHECKING, Any, Callable, Protocol, Union import httpx from typing_extensions import NotRequired, TypedDict from .. ...
--- +++ @@ -51,6 +51,11 @@ class HttpClientFactory(Protocol): + """Protocol for HTTP client factory functions. + + This interface matches the MCP SDK's McpHttpClientFactory but is defined locally + to avoid accessing internal MCP SDK modules. + """ def __call__( self, @@ -62,6 +67,7 @@ ...
https://raw.githubusercontent.com/openai/openai-agents-python/HEAD/src/agents/mcp/util.py
Can you add docstrings to this Python file?
from __future__ import annotations from collections.abc import Sequence from typing import Any, Literal, cast from typing_extensions import Required, TypedDict from .exceptions import UserError BareFunctionToolLookupKey = tuple[Literal["bare"], str] NamespacedFunctionToolLookupKey = tuple[Literal["namespaced"], str...
--- +++ @@ -19,6 +19,7 @@ class SerializedFunctionToolLookupKey(TypedDict, total=False): + """Serialized representation of a function-tool lookup key.""" kind: Required[Literal["bare", "namespaced", "deferred_top_level"]] name: Required[str] @@ -26,12 +27,14 @@ def get_mapping_or_attr(value: Any,...
https://raw.githubusercontent.com/openai/openai-agents-python/HEAD/src/agents/_tool_identity.py
Create docstrings for each class method
from __future__ import annotations import dataclasses import inspect from collections.abc import Awaitable from dataclasses import dataclass, field from typing import Any, Callable, Generic, cast from agents.prompts import Prompt from ..agent import AgentBase from ..guardrail import OutputGuardrail from ..handoffs i...
--- +++ @@ -25,6 +25,21 @@ @dataclass class RealtimeAgent(AgentBase, Generic[TContext]): + """A specialized agent instance that is meant to be used within a `RealtimeSession` to build + voice agents. Due to the nature of this agent, some configuration options are not supported + that are supported by regula...
https://raw.githubusercontent.com/openai/openai-agents-python/HEAD/src/agents/realtime/agent.py
Write docstrings describing functionality
from __future__ import annotations import abc import enum from collections.abc import AsyncIterator from typing import TYPE_CHECKING from openai.types.responses.response_prompt_param import ResponsePromptParam from ..agent_output import AgentOutputSchemaBase from ..handoffs import Handoff from ..items import ModelRe...
--- +++ @@ -35,11 +35,22 @@ class Model(abc.ABC): + """The base interface for calling an LLM.""" async def close(self) -> None: + """Release any resources held by the model. + + Models that maintain persistent connections can override this. The default implementation + is a no-op. + ...
https://raw.githubusercontent.com/openai/openai-agents-python/HEAD/src/agents/models/interface.py
Add docstrings explaining edge cases
from __future__ import annotations import asyncio from collections.abc import Awaitable, Callable, Iterable from contextlib import AbstractAsyncContextManager from dataclasses import dataclass from typing import Any from ..logger import logger from .server import MCPServer @dataclass class _ServerCommand: actio...
--- +++ @@ -106,6 +106,42 @@ class MCPServerManager(AbstractAsyncContextManager["MCPServerManager"]): + """Manage MCP server lifecycles and expose only connected servers. + + Use this helper to keep MCP connect/cleanup on the same task and avoid + run failures when a server is unavailable. The manager will...
https://raw.githubusercontent.com/openai/openai-agents-python/HEAD/src/agents/mcp/manager.py
Add docstrings to improve readability
from __future__ import annotations import graphviz # type: ignore from agents import Agent from agents.handoffs import Handoff def get_main_graph(agent: Agent) -> str: parts = [ """ digraph G { graph [splines=true]; node [fontname="Arial"]; edge [penwidth=1.5]; """ ]...
--- +++ @@ -7,6 +7,15 @@ def get_main_graph(agent: Agent) -> str: + """ + Generates the main graph structure in DOT format for the given agent. + + Args: + agent (Agent): The agent for which the graph is to be generated. + + Returns: + str: The DOT format string representing the graph. + ...
https://raw.githubusercontent.com/openai/openai-agents-python/HEAD/src/agents/extensions/visualization.py
Please document this code using docstrings
from __future__ import annotations import dataclasses from dataclasses import fields, replace from typing import Any from pydantic.dataclasses import dataclass def resolve_session_limit( explicit_limit: int | None, settings: SessionSettings | None, ) -> int | None: if explicit_limit is not None: ...
--- +++ @@ -1,3 +1,4 @@+"""Session configuration settings.""" from __future__ import annotations @@ -12,6 +13,7 @@ explicit_limit: int | None, settings: SessionSettings | None, ) -> int | None: + """Safely resolve the effective limit for session operations.""" if explicit_limit is not None: ...
https://raw.githubusercontent.com/openai/openai-agents-python/HEAD/src/agents/memory/session_settings.py
Generate consistent docstrings
from __future__ import annotations import asyncio import json import random import time from typing import Any, Final, Literal try: from dapr.aio.clients import DaprClient from dapr.clients.grpc._state import Concurrency, Consistency, StateOptions except ImportError as e: raise ImportError( "Dapr...
--- +++ @@ -1,3 +1,25 @@+"""Dapr State Store-powered Session backend. + +Usage:: + + from agents.extensions.memory import DaprSession + + # Create from Dapr sidecar address + session = DaprSession.from_address( + session_id="user-123", + state_store_name="statestore", + dapr_address="local...
https://raw.githubusercontent.com/openai/openai-agents-python/HEAD/src/agents/extensions/memory/dapr_session.py
Generate docstrings for exported functions
from __future__ import annotations from dataclasses import dataclass from typing import Any, Literal, Union from typing_extensions import NotRequired, TypeAlias, TypedDict from .config import RealtimeSessionModelSettings from .model_events import RealtimeModelToolCallEvent class RealtimeModelRawClientMessage(Typed...
--- +++ @@ -10,6 +10,7 @@ class RealtimeModelRawClientMessage(TypedDict): + """A raw message to be sent to the model.""" type: str # explicitly required other_data: NotRequired[dict[str, Any]] @@ -17,12 +18,17 @@ class RealtimeModelInputTextContent(TypedDict): + """A piece of text to be sent ...
https://raw.githubusercontent.com/openai/openai-agents-python/HEAD/src/agents/realtime/model_inputs.py
Add inline docstrings for readability
from __future__ import annotations import contextlib import inspect import logging import re from dataclasses import dataclass from typing import Annotated, Any, Callable, Literal, get_args, get_origin, get_type_hints from griffe import Docstring, DocstringSectionKind from pydantic import BaseModel, Field, create_mod...
--- +++ @@ -19,6 +19,9 @@ @dataclass class FuncSchema: + """ + Captures the schema for a python function, in preparation for sending it to an LLM as a tool. + """ name: str """The name of the function.""" @@ -37,6 +40,10 @@ as it increases the likelihood of correct JSON input.""" def ...
https://raw.githubusercontent.com/openai/openai-agents-python/HEAD/src/agents/function_schema.py
Generate descriptive docstrings automatically
from __future__ import annotations from ..run_context import TContext from .agent import RealtimeAgent from .config import ( RealtimeRunConfig, ) from .model import ( RealtimeModel, RealtimeModelConfig, ) from .openai_realtime import OpenAIRealtimeWebSocketModel from .session import RealtimeSession clas...
--- +++ @@ -1,3 +1,4 @@+"""Minimal realtime session implementation for voice agents.""" from __future__ import annotations @@ -15,6 +16,16 @@ class RealtimeRunner: + """A `RealtimeRunner` is the equivalent of `Runner` for realtime agents. It automatically + handles multiple turns by maintaining a persist...
https://raw.githubusercontent.com/openai/openai-agents-python/HEAD/src/agents/realtime/runner.py
Generate docstrings with parameter types
from __future__ import annotations import asyncio import base64 import inspect import json import math import os from collections.abc import Mapping from datetime import datetime from typing import Annotated, Any, Callable, Literal, Union, cast import pydantic import websockets from openai.types.realtime import realt...
--- +++ @@ -253,6 +253,7 @@ class TransportConfig(TypedDict): + """Low-level network transport configuration.""" ping_interval: NotRequired[float | None] """Time in seconds between keepalive pings sent by the client. @@ -267,6 +268,7 @@ class OpenAIRealtimeWebSocketModel(RealtimeModel): + """A...
https://raw.githubusercontent.com/openai/openai-agents-python/HEAD/src/agents/realtime/openai_realtime.py
Create docstrings for API functions
from __future__ import annotations import inspect import json from collections.abc import Awaitable from dataclasses import dataclass from typing import Any, Callable, TypedDict, Union, cast from pydantic import BaseModel from .items import TResponseInputItem STRUCTURED_INPUT_PREAMBLE = ( "You are being called ...
--- +++ @@ -19,18 +19,21 @@ class AgentAsToolInput(BaseModel): + """Default input schema for agent-as-tool calls.""" input: str @dataclass(frozen=True) class StructuredInputSchemaInfo: + """Optional schema details used to build structured tool input.""" summary: str | None = None json...
https://raw.githubusercontent.com/openai/openai-agents-python/HEAD/src/agents/agent_tool_input.py
Document functions with detailed explanations
from __future__ import annotations import asyncio import contextlib import inspect import json import weakref from collections.abc import AsyncIterator, Awaitable, Callable, Mapping, Sequence from contextvars import ContextVar from dataclasses import asdict, dataclass, is_dataclass from enum import Enum from typing im...
--- +++ @@ -156,6 +156,7 @@ async def _refresh_openai_client_api_key_if_supported(client: Any) -> None: + """Refresh client auth if the current OpenAI SDK exposes a refresh hook.""" refresh_api_key = getattr(client, "_refresh_api_key", None) if callable(refresh_api_key): await refresh_api_key(...
https://raw.githubusercontent.com/openai/openai-agents-python/HEAD/src/agents/models/openai_responses.py
Document functions with detailed explanations
from __future__ import annotations import sys from dataclasses import dataclass from typing import Literal, Protocol, runtime_checkable from .run_context import RunContextWrapper from .util._types import MaybeAwaitable ApplyPatchOperationType = Literal["create_file", "update_file", "delete_file"] _DATACLASS_KWARGS ...
--- +++ @@ -14,6 +14,7 @@ @dataclass(**_DATACLASS_KWARGS) class ApplyPatchOperation: + """Represents a single apply_patch editor operation requested by the model.""" type: ApplyPatchOperationType path: str @@ -23,6 +24,7 @@ @dataclass(**_DATACLASS_KWARGS) class ApplyPatchResult: + """Optional me...
https://raw.githubusercontent.com/openai/openai-agents-python/HEAD/src/agents/editor.py
Create docstrings for API functions
from __future__ import annotations import base64 import json from typing import Any, cast from cryptography.fernet import Fernet, InvalidToken from cryptography.hazmat.primitives import hashes from cryptography.hazmat.primitives.kdf.hkdf import HKDF from typing_extensions import Literal, TypedDict, TypeGuard from ....
--- +++ @@ -1,143 +1,196 @@- -from __future__ import annotations - -import base64 -import json -from typing import Any, cast - -from cryptography.fernet import Fernet, InvalidToken -from cryptography.hazmat.primitives import hashes -from cryptography.hazmat.primitives.kdf.hkdf import HKDF -from typing_extensions import...
https://raw.githubusercontent.com/openai/openai-agents-python/HEAD/src/agents/extensions/memory/encrypt_session.py
Add docstrings that explain purpose and usage
from __future__ import annotations import asyncio import os import weakref import httpx from openai import AsyncOpenAI, DefaultAsyncHttpxClient from . import _openai_shared from .default_models import get_default_model from .interface import Model, ModelProvider from .openai_chatcompletions import OpenAIChatCompleti...
--- +++ @@ -44,6 +44,23 @@ use_responses: bool | None = None, use_responses_websocket: bool | None = None, ) -> None: + """Create a new OpenAI provider. + + Args: + api_key: The API key to use for the OpenAI client. If not provided, we will use the + default...
https://raw.githubusercontent.com/openai/openai-agents-python/HEAD/src/agents/models/openai_provider.py
Generate NumPy-style docstrings
from __future__ import annotations import asyncio import json import time from typing import Any try: import redis.asyncio as redis from redis.asyncio import Redis except ImportError as e: raise ImportError( "RedisSession requires the 'redis' package. Install it with: pip install redis" ) fro...
--- +++ @@ -1,3 +1,23 @@+"""Redis-powered Session backend. + +Usage:: + + from agents.extensions.memory import RedisSession + + # Create from Redis URL + session = RedisSession.from_url( + session_id="user-123", + url="redis://localhost:6379/0", + ) + + # Or pass an existing Redis client th...
https://raw.githubusercontent.com/openai/openai-agents-python/HEAD/src/agents/extensions/memory/redis_session.py
Document this script properly
from __future__ import annotations from collections.abc import Mapping from typing import Any, Literal, Union from openai.types.realtime.realtime_audio_formats import ( RealtimeAudioFormats as OpenAIRealtimeAudioFormats, ) from typing_extensions import NotRequired, TypeAlias, TypedDict from agents.prompts import...
--- +++ @@ -46,6 +46,7 @@ class RealtimeClientMessage(TypedDict): + """A raw message to be sent to the model.""" type: str # explicitly required """The type of the message.""" @@ -55,6 +56,7 @@ class RealtimeInputAudioTranscriptionConfig(TypedDict): + """Configuration for audio transcription ...
https://raw.githubusercontent.com/openai/openai-agents-python/HEAD/src/agents/realtime/config.py
Add professional docstrings to my codebase
from __future__ import annotations from dataclasses import dataclass from typing import Any, Literal, Union from typing_extensions import TypeAlias from .items import RealtimeItem RealtimeConnectionStatus: TypeAlias = Literal["connecting", "connected", "disconnected"] @dataclass class RealtimeModelErrorEvent: ...
--- +++ @@ -12,6 +12,7 @@ @dataclass class RealtimeModelErrorEvent: + """Represents a transport‑layer error.""" error: Any @@ -20,6 +21,7 @@ @dataclass class RealtimeModelToolCallEvent: + """Model attempted a tool/function call.""" name: str call_id: str @@ -33,6 +35,7 @@ @dataclass ...
https://raw.githubusercontent.com/openai/openai-agents-python/HEAD/src/agents/realtime/model_events.py
Write proper docstrings for these functions
from __future__ import annotations from typing import Annotated, Literal, Union from pydantic import BaseModel, ConfigDict, Field class InputText(BaseModel): type: Literal["input_text"] = "input_text" """The type identifier for text input.""" text: str | None = None """The text content.""" # ...
--- +++ @@ -6,6 +6,7 @@ class InputText(BaseModel): + """Text input content for realtime messages.""" type: Literal["input_text"] = "input_text" """The type identifier for text input.""" @@ -18,6 +19,7 @@ class InputAudio(BaseModel): + """Audio input content for realtime messages.""" ty...
https://raw.githubusercontent.com/openai/openai-agents-python/HEAD/src/agents/realtime/items.py
Write documentation strings for class attributes
from __future__ import annotations import asyncio import json from collections.abc import AsyncIterator from contextlib import asynccontextmanager from pathlib import Path from typing import cast import aiosqlite from ...items import TResponseInputItem from ...memory import SessionABC from ...memory.session_settings...
--- +++ @@ -15,6 +15,12 @@ class AsyncSQLiteSession(SessionABC): + """Async SQLite-based implementation of session storage. + + This implementation stores conversation history in a SQLite database. + By default, uses an in-memory database that is lost when the process ends. + For persistent storage, pro...
https://raw.githubusercontent.com/openai/openai-agents-python/HEAD/src/agents/extensions/memory/async_sqlite_session.py
Help me comply with documentation standards
from __future__ import annotations from collections.abc import Mapping from dataclasses import fields, replace from typing import Annotated, Any, Literal, Union, cast from openai import Omit as _Omit from openai._types import Body, Query from openai.types.responses import ResponseIncludable from openai.types.shared i...
--- +++ @@ -63,6 +63,14 @@ @dataclass class ModelSettings: + """Settings to use when calling an LLM. + + This class holds optional model configuration parameters (e.g. temperature, + top_p, penalties, truncation, etc.). + + Not all models/providers support all of these parameters, so please check the API...
https://raw.githubusercontent.com/openai/openai-agents-python/HEAD/src/agents/model_settings.py
Document helper functions with docstrings
from __future__ import annotations import json from copy import deepcopy from typing import TYPE_CHECKING, Any, cast from ..items import ( ItemHelpers, RunItem, ToolApprovalItem, TResponseInputItem, ) if TYPE_CHECKING: from . import HandoffHistoryMapper, HandoffInputData __all__ = [ "default...
--- +++ @@ -42,6 +42,10 @@ start: str | None = None, end: str | None = None, ) -> None: + """Override the markers that wrap the generated conversation summary. + + Pass ``None`` to leave either side unchanged. + """ global _conversation_history_start, _conversation_history_end if start is...
https://raw.githubusercontent.com/openai/openai-agents-python/HEAD/src/agents/handoffs/history.py
Create docstrings for reusable components
import copy import os from typing import Optional from openai.types.shared.reasoning import Reasoning from agents.model_settings import ModelSettings OPENAI_DEFAULT_MODEL_ENV_VARIABLE_NAME = "OPENAI_DEFAULT_MODEL" # discourage directly accessing this constant # use the get_default_model and get_default_model_settin...
--- +++ @@ -30,6 +30,9 @@ def gpt_5_reasoning_settings_required(model_name: str) -> bool: + """ + Returns True if the model name is a GPT-5 model and reasoning settings are required. + """ if model_name.startswith("gpt-5-chat"): # gpt-5-chat-latest does not require reasoning settings ...
https://raw.githubusercontent.com/openai/openai-agents-python/HEAD/src/agents/models/default_models.py
Add docstrings including usage examples
from __future__ import annotations from dataclasses import dataclass from typing import Any, Literal, Union from typing_extensions import TypeAlias from ..guardrail import OutputGuardrailResult from ..run_context import RunContextWrapper from ..tool import Tool from .agent import RealtimeAgent from .items import Rea...
--- +++ @@ -21,6 +21,7 @@ @dataclass class RealtimeAgentStartEvent: + """A new agent has started.""" agent: RealtimeAgent """The new agent.""" @@ -33,6 +34,7 @@ @dataclass class RealtimeAgentEndEvent: + """An agent has ended.""" agent: RealtimeAgent """The agent that ended.""" @@ -45...
https://raw.githubusercontent.com/openai/openai-agents-python/HEAD/src/agents/realtime/events.py
Help me comply with documentation standards
from __future__ import annotations import json import os import time from collections.abc import AsyncIterator from copy import copy from typing import Any, Literal, cast, overload from openai.types.responses.response_usage import InputTokensDetails, OutputTokensDetails from agents.exceptions import ModelBehaviorErr...
--- +++ @@ -59,6 +59,7 @@ def _patch_litellm_serializer_warnings() -> None: + """Ensure LiteLLM logging uses model_dump(warnings=False) when available.""" # Background: LiteLLM emits Pydantic serializer warnings for Message/Choices mismatches. # See: https://github.com/BerriAI/litellm/issues/11759 ...
https://raw.githubusercontent.com/openai/openai-agents-python/HEAD/src/agents/extensions/models/litellm_model.py
Write docstrings for algorithm functions
from __future__ import annotations import inspect import json import weakref from collections.abc import Awaitable from dataclasses import dataclass, field, replace as dataclasses_replace from typing import TYPE_CHECKING, Any, Callable, Generic, cast, overload from pydantic import TypeAdapter from typing_extensions i...
--- +++ @@ -71,6 +71,14 @@ """ def clone(self, **kwargs: Any) -> HandoffInputData: + """ + Make a copy of the handoff input data, with the given arguments changed. For example, you + could do: + + ``` + new_handoff_input_data = handoff_input_data.clone(new_items=()) + ...
https://raw.githubusercontent.com/openai/openai-agents-python/HEAD/src/agents/handoffs/__init__.py
Write Python docstrings for this snippet
from __future__ import annotations from typing import Literal, cast from openai import AsyncOpenAI from ..exceptions import UserError from .interface import Model, ModelProvider from .openai_provider import OpenAIProvider MultiProviderOpenAIPrefixMode = Literal["alias", "model_id"] MultiProviderUnknownPrefixMode = ...
--- +++ @@ -13,30 +13,61 @@ class MultiProviderMap: + """A map of model name prefixes to ModelProviders.""" def __init__(self): self._mapping: dict[str, ModelProvider] = {} def has_prefix(self, prefix: str) -> bool: + """Returns True if the given prefix is in the mapping.""" ...
https://raw.githubusercontent.com/openai/openai-agents-python/HEAD/src/agents/models/multi_provider.py
Include argument descriptions in docstrings
from __future__ import annotations import abc import asyncio import inspect import sys from collections.abc import Awaitable from contextlib import AbstractAsyncContextManager, AsyncExitStack, asynccontextmanager from datetime import timedelta from pathlib import Path from typing import TYPE_CHECKING, Any, Callable, L...
--- +++ @@ -62,9 +62,11 @@ class _SharedSessionRequestNeedsIsolation(Exception): + """Raised when a shared-session request should be retried on an isolated session.""" class _IsolatedSessionRetryFailed(Exception): + """Raised when an isolated-session retry fails after consuming retry budget.""" clas...
https://raw.githubusercontent.com/openai/openai-agents-python/HEAD/src/agents/mcp/server.py
Write docstrings for backend logic
from __future__ import annotations import inspect from dataclasses import dataclass from typing import TYPE_CHECKING, Any, Callable, cast from openai.types.responses.response_prompt_param import ( ResponsePromptParam, Variables as ResponsesPromptVariables, ) from typing_extensions import NotRequired, TypedDic...
--- +++ @@ -20,6 +20,7 @@ class Prompt(TypedDict): + """Prompt configuration to use for interacting with an OpenAI model.""" id: str """The unique ID of the prompt.""" @@ -33,6 +34,7 @@ @dataclass class GenerateDynamicPromptData: + """Inputs to a function that allows you to dynamically generate...
https://raw.githubusercontent.com/openai/openai-agents-python/HEAD/src/agents/prompts.py
Provide docstrings following PEP 257
from __future__ import annotations from abc import ABC, abstractmethod from typing import TYPE_CHECKING, Literal, Protocol, runtime_checkable from typing_extensions import TypedDict, TypeGuard if TYPE_CHECKING: from ..items import TResponseInputItem from .session_settings import SessionSettings @runtime_ch...
--- +++ @@ -12,46 +12,100 @@ @runtime_checkable class Session(Protocol): + """Protocol for session implementations. + + Session stores conversation history for a specific session, allowing + agents to maintain context without requiring explicit manual memory management. + """ session_id: str ...
https://raw.githubusercontent.com/openai/openai-agents-python/HEAD/src/agents/memory/session.py
Replace inline comments with docstrings
import logging import sys from typing import Literal from openai import AsyncOpenAI from . import _config from .agent import ( Agent, AgentBase, AgentToolStreamEvent, StopAtTools, ToolsToFinalOutputFunction, ToolsToFinalOutputResult, ) from .agent_output import AgentOutputSchema, AgentOutputSc...
--- +++ @@ -226,22 +226,51 @@ def set_default_openai_key(key: str, use_for_tracing: bool = True) -> None: + """Set the default OpenAI API key to use for LLM requests (and optionally tracing()). This is + only necessary if the OPENAI_API_KEY environment variable is not already set. + + If provided, this key...
https://raw.githubusercontent.com/openai/openai-agents-python/HEAD/src/agents/__init__.py
Add detailed documentation for each class
from __future__ import annotations import abc from typing import Callable from typing_extensions import NotRequired, TypedDict from ..util._types import MaybeAwaitable from ._util import calculate_audio_length_ms from .config import ( RealtimeAudioFormat, RealtimeSessionModelSettings, ) from .model_events im...
--- +++ @@ -27,6 +27,10 @@ class RealtimePlaybackTracker: + """If you have custom playback logic or expect that audio is played with delays or at different + speeds, create an instance of RealtimePlaybackTracker and pass it to the session. You are + responsible for tracking the audio playback progress and ...
https://raw.githubusercontent.com/openai/openai-agents-python/HEAD/src/agents/realtime/model.py
Add docstrings to my Python code
from __future__ import annotations import json from collections.abc import Iterable from typing import Any, Literal, Union, cast from openai import Omit, omit from openai.types.chat import ( ChatCompletionAssistantMessageParam, ChatCompletionContentPartImageParam, ChatCompletionContentPartInputAudioParam,...
--- +++ @@ -112,6 +112,15 @@ message: ChatCompletionMessage, provider_data: dict[str, Any] | None = None, ) -> list[TResponseOutputItem]: + """ + Convert a ChatCompletionMessage to a list of response output items. + + Args: + message: The chat completion message to ...
https://raw.githubusercontent.com/openai/openai-agents-python/HEAD/src/agents/models/chatcmpl_converter.py
Create docstrings for all classes and functions
from __future__ import annotations from openai import AsyncOpenAI from agents.models._openai_shared import get_default_openai_client from ..items import TResponseInputItem from .session import SessionABC from .session_settings import SessionSettings, resolve_session_limit async def start_openai_conversations_sessi...
--- +++ @@ -40,6 +40,16 @@ @property def session_id(self) -> str: + """Get the session ID (conversation ID). + + Returns: + The conversation ID for this session. + + Raises: + ValueError: If the session has not been initialized yet. + Call any session...
https://raw.githubusercontent.com/openai/openai-agents-python/HEAD/src/agents/memory/openai_conversations_session.py
Write docstrings for backend logic
from __future__ import annotations import weakref from typing import TYPE_CHECKING, Any if TYPE_CHECKING: from openai.types.responses.response_function_tool_call import ResponseFunctionToolCall from .result import RunResult, RunResultStreaming ToolCallSignature = tuple[str, str, str, str, str | None, str | ...
--- +++ @@ -28,11 +28,13 @@ def get_agent_tool_state_scope(context: Any) -> str | None: + """Read the private agent-tool cache scope id from a context wrapper.""" scope_id = getattr(context, _AGENT_TOOL_STATE_SCOPE_ATTR, None) return scope_id if isinstance(scope_id, str) else None def set_agent_to...
https://raw.githubusercontent.com/openai/openai-agents-python/HEAD/src/agents/agent_tool_state.py
Add professional docstrings to my codebase
from __future__ import annotations import asyncio import dataclasses import inspect from collections.abc import Awaitable from dataclasses import dataclass, field from typing import TYPE_CHECKING, Any, Callable, Generic, Literal, cast from openai.types.responses.response_prompt_param import ResponsePromptParam from p...
--- +++ @@ -119,6 +119,7 @@ class AgentToolStreamEvent(TypedDict): + """Streaming event emitted when an agent is invoked as a tool.""" event: StreamEvent """The streaming event from the nested agent run.""" @@ -136,6 +137,7 @@ class MCPConfig(TypedDict): + """Configuration for MCP servers.""" ...
https://raw.githubusercontent.com/openai/openai-agents-python/HEAD/src/agents/agent.py
Document all endpoints with docstrings
from __future__ import annotations import dataclasses from collections.abc import Callable, Iterable from dataclasses import dataclass, field from inspect import isawaitable from typing import Any from pydantic import Field from pydantic.dataclasses import dataclass as pydantic_dataclass from typing_extensions import...
--- +++ @@ -15,6 +15,7 @@ @pydantic_dataclass class ModelRetryBackoffSettings: + """Backoff configuration for runner-managed model retries.""" initial_delay: float | None = None """Delay in seconds before the first retry attempt.""" @@ -48,6 +49,7 @@ @dataclass(init=False) class ModelRetryNormalize...
https://raw.githubusercontent.com/openai/openai-agents-python/HEAD/src/agents/retry.py
Document my Python code with docstrings
#!/usr/bin/env python from pathlib import Path # ---- Paths ----------------------------------------------------------- REPO_ROOT = Path(__file__).resolve().parent.parent.parent # adjust if layout differs SRC_ROOT = REPO_ROOT / "src" / "agents" # source tree to scan DOCS_ROOT = REPO_ROOT / "docs" / "ref" # where ...
--- +++ @@ -1,4 +1,12 @@ #!/usr/bin/env python +""" +generate_ref_files.py + +Create missing Markdown reference stubs for mkdocstrings. + +Usage: + python scripts/generate_ref_files.py +""" from pathlib import Path @@ -12,16 +20,22 @@ def to_identifier(py_path: Path) -> str: + """Convert src/agents/foo/b...
https://raw.githubusercontent.com/openai/openai-agents-python/HEAD/docs/scripts/generate_ref_files.py
Help me document legacy Python code
from __future__ import annotations import asyncio import dataclasses import inspect import json from collections.abc import AsyncIterator from typing import Any, cast from pydantic import BaseModel from typing_extensions import assert_never from .._tool_identity import get_function_tool_lookup_key_for_tool from ..ag...
--- +++ @@ -71,6 +71,7 @@ def _serialize_tool_output(output: Any) -> str: + """Serialize structured tool outputs to JSON when possible.""" if isinstance(output, str): return output if isinstance(output, BaseModel): @@ -93,6 +94,24 @@ class RealtimeSession(RealtimeModelListener): + """A ...
https://raw.githubusercontent.com/openai/openai-agents-python/HEAD/src/agents/realtime/session.py