code
stringlengths
66
870k
docstring
stringlengths
19
26.7k
func_name
stringlengths
1
138
language
stringclasses
1 value
repo
stringlengths
7
68
path
stringlengths
5
324
url
stringlengths
46
389
license
stringclasses
7 values
def export(path=None, user_content=False, context=None, username=None, password=None, render_offline=False, render_wide=False, render_inline=True, out_filename=None, api_url=None, title=None, quiet=False, theme='light', grip_class=None): """ Exports the rendered HTML to a file. ...
Exports the rendered HTML to a file.
export
python
joeyespo/grip
grip/api.py
https://github.com/joeyespo/grip/blob/master/grip/api.py
MIT
def _get_styles(self, style_urls, asset_url_path): """ Gets the content of the given list of style URLs and inlines assets. """ styles = [] for style_url in style_urls: urls_inline = STYLE_ASSET_URLS_INLINE_FORMAT.format( asset_url_path.rstrip(...
Gets the content of the given list of style URLs and inlines assets.
_get_styles
python
joeyespo/grip
grip/app.py
https://github.com/joeyespo/grip/blob/master/grip/app.py
MIT
def _inline_styles(self): """ Downloads the assets from the style URL list, clears it, and adds each style with its embedded asset to the literal style list. """ styles = self._get_styles(self.assets.style_urls, url_for('asset')) self.assets.styles.extend(styles) ...
Downloads the assets from the style URL list, clears it, and adds each style with its embedded asset to the literal style list.
_inline_styles
python
joeyespo/grip
grip/app.py
https://github.com/joeyespo/grip/blob/master/grip/app.py
MIT
def _retrieve_styles(self): """ Retrieves the style URLs from the source and caches them. This is called before the first request is dispatched. """ if self._styles_retrieved: return self._styles_retrieved = True try: self.assets.retrieve_...
Retrieves the style URLs from the source and caches them. This is called before the first request is dispatched.
_retrieve_styles
python
joeyespo/grip
grip/app.py
https://github.com/joeyespo/grip/blob/master/grip/app.py
MIT
def default_asset_manager(self): """ Returns the default asset manager using the current config. This is only used if asset_manager is set to None in the constructor. """ cache_path = None cache_directory = self.config['CACHE_DIRECTORY'] if cache_directory: ...
Returns the default asset manager using the current config. This is only used if asset_manager is set to None in the constructor.
default_asset_manager
python
joeyespo/grip
grip/app.py
https://github.com/joeyespo/grip/blob/master/grip/app.py
MIT
def render(self, route=None): """ Renders the application and returns the HTML unicode that would normally appear when visiting in the browser. """ if route is None: route = '/' with self.test_client() as c: response = c.get(route, follow_redirects...
Renders the application and returns the HTML unicode that would normally appear when visiting in the browser.
render
python
joeyespo/grip
grip/app.py
https://github.com/joeyespo/grip/blob/master/grip/app.py
MIT
def run(self, host=None, port=None, debug=None, use_reloader=None, open_browser=False): """ Starts a server to render the README. """ if host is None: host = self.config['HOST'] if port is None: port = self.config['PORT'] if debug is No...
Starts a server to render the README.
run
python
joeyespo/grip
grip/app.py
https://github.com/joeyespo/grip/blob/master/grip/app.py
MIT
def cache_filename(self, url): """ Gets a suitable relative filename for the specified URL. """ # FUTURE: Use url exactly instead of flattening it here url = posixpath.basename(url) return self._strip_url_params(url)
Gets a suitable relative filename for the specified URL.
cache_filename
python
joeyespo/grip
grip/assets.py
https://github.com/joeyespo/grip/blob/master/grip/assets.py
MIT
def _get_style_urls(self, asset_url_path): """ Gets the specified resource and parses all style URLs and their assets in the form of the specified patterns. """ # Check cache if self.cache_path: cached = self._get_cached_style_urls(asset_url_path) ...
Gets the specified resource and parses all style URLs and their assets in the form of the specified patterns.
_get_style_urls
python
joeyespo/grip
grip/assets.py
https://github.com/joeyespo/grip/blob/master/grip/assets.py
MIT
def _get_cached_style_urls(self, asset_url_path): """ Gets the URLs of the cached styles. """ try: cached_styles = os.listdir(self.cache_path) except IOError as ex: if ex.errno != errno.ENOENT and ex.errno != errno.ESRCH: raise ...
Gets the URLs of the cached styles.
_get_cached_style_urls
python
joeyespo/grip
grip/assets.py
https://github.com/joeyespo/grip/blob/master/grip/assets.py
MIT
def _cache_contents(self, style_urls, asset_url_path): """ Fetches the given URLs and caches their contents and their assets in the given directory. """ files = {} asset_urls = [] for style_url in style_urls: if not self.quiet: print('...
Fetches the given URLs and caches their contents and their assets in the given directory.
_cache_contents
python
joeyespo/grip
grip/assets.py
https://github.com/joeyespo/grip/blob/master/grip/assets.py
MIT
def retrieve_styles(self, asset_url_path): """ Get style URLs from the source HTML page and specified cached asset base URL. """ if not asset_url_path.endswith('/'): asset_url_path += '/' self.style_urls.extend(self._get_style_urls(asset_url_path))
Get style URLs from the source HTML page and specified cached asset base URL.
retrieve_styles
python
joeyespo/grip
grip/assets.py
https://github.com/joeyespo/grip/blob/master/grip/assets.py
MIT
def is_server_running(host, port): """ Checks whether a server is currently listening on the specified host and port. """ s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) try: return s.connect_ex((host, port)) == 0 finally: s.close()
Checks whether a server is currently listening on the specified host and port.
is_server_running
python
joeyespo/grip
grip/browser.py
https://github.com/joeyespo/grip/blob/master/grip/browser.py
MIT
def wait_for_server(host, port, cancel_event=None): """ Blocks until a local server is listening on the specified host and port. Set cancel_event to cancel the wait. This is intended to be used in conjunction with running the Flask server. """ while not is_server_running(host, port): ...
Blocks until a local server is listening on the specified host and port. Set cancel_event to cancel the wait. This is intended to be used in conjunction with running the Flask server.
wait_for_server
python
joeyespo/grip
grip/browser.py
https://github.com/joeyespo/grip/blob/master/grip/browser.py
MIT
def start_browser(url): """ Opens the specified URL in a new browser window. """ try: webbrowser.open(url) except Exception: pass
Opens the specified URL in a new browser window.
start_browser
python
joeyespo/grip
grip/browser.py
https://github.com/joeyespo/grip/blob/master/grip/browser.py
MIT
def wait_and_start_browser(host, port=None, cancel_event=None): """ Waits for the server to run and then opens the specified address in the browser. Set cancel_event to cancel the wait. """ if host == '0.0.0.0': host = 'localhost' if port is None: port = 80 if wait_for_serve...
Waits for the server to run and then opens the specified address in the browser. Set cancel_event to cancel the wait.
wait_and_start_browser
python
joeyespo/grip
grip/browser.py
https://github.com/joeyespo/grip/blob/master/grip/browser.py
MIT
def start_browser_when_ready(host, port=None, cancel_event=None): """ Starts a thread that waits for the server then opens the specified address in the browser. Set cancel_event to cancel the wait. The started thread object is returned. """ browser_thread = Thread( target=wait_and_start_...
Starts a thread that waits for the server then opens the specified address in the browser. Set cancel_event to cancel the wait. The started thread object is returned.
start_browser_when_ready
python
joeyespo/grip
grip/browser.py
https://github.com/joeyespo/grip/blob/master/grip/browser.py
MIT
def main(argv=None, force_utf8=True, patch_svg=True): """ The entry point of the application. """ if force_utf8 and sys.version_info[0] == 2: reload(sys) # noqa sys.setdefaultencoding('utf-8') if patch_svg and sys.version_info[0] == 2 and sys.version_info[1] <= 6: mimetypes....
The entry point of the application.
main
python
joeyespo/grip
grip/command.py
https://github.com/joeyespo/grip/blob/master/grip/command.py
MIT
def patch(html, user_content=False): """ Processes the HTML rendered by the GitHub API, patching any inconsistencies from the main site. """ # FUTURE: Remove this once GitHub API renders task lists # https://github.com/isaacs/github/issues/309 if not user_content: html = INCOMPLETE_T...
Processes the HTML rendered by the GitHub API, patching any inconsistencies from the main site.
patch
python
joeyespo/grip
grip/patcher.py
https://github.com/joeyespo/grip/blob/master/grip/patcher.py
MIT
def normalize_subpath(self, subpath): """ Returns the normalized subpath. This allows Readme files to be inferred from directories while still allowing relative paths to work properly. Override to change the default behavior of returning the specified subpath as-is. ...
Returns the normalized subpath. This allows Readme files to be inferred from directories while still allowing relative paths to work properly. Override to change the default behavior of returning the specified subpath as-is.
normalize_subpath
python
joeyespo/grip
grip/readers.py
https://github.com/joeyespo/grip/blob/master/grip/readers.py
MIT
def mimetype_for(self, subpath=None): """ Gets the mimetype for the specified subpath. """ if subpath is None: subpath = DEFAULT_FILENAME mimetype, _ = mimetypes.guess_type(subpath) return mimetype
Gets the mimetype for the specified subpath.
mimetype_for
python
joeyespo/grip
grip/readers.py
https://github.com/joeyespo/grip/blob/master/grip/readers.py
MIT
def _find_file(self, path, silent=False): """ Gets the full path and extension, or None if a README file could not be found at the specified path. """ for filename in DEFAULT_FILENAMES: full_path = os.path.join(path, filename) if path else filename if os.p...
Gets the full path and extension, or None if a README file could not be found at the specified path.
_find_file
python
joeyespo/grip
grip/readers.py
https://github.com/joeyespo/grip/blob/master/grip/readers.py
MIT
def _resolve_readme(self, path=None, silent=False): """ Returns the path if it's a file; otherwise, looks for a compatible README file in the directory specified by path. If path is None, the current working directory is used. If silent is set, the default relative filename wil...
Returns the path if it's a file; otherwise, looks for a compatible README file in the directory specified by path. If path is None, the current working directory is used. If silent is set, the default relative filename will be returned if path is a directory or None if it does...
_resolve_readme
python
joeyespo/grip
grip/readers.py
https://github.com/joeyespo/grip/blob/master/grip/readers.py
MIT
def normalize_subpath(self, subpath): """ Normalizes the specified subpath, or None if subpath is None. This allows Readme files to be inferred from directories while still allowing relative paths to work properly. Raises werkzeug.exceptions.NotFound if the resulting path ...
Normalizes the specified subpath, or None if subpath is None. This allows Readme files to be inferred from directories while still allowing relative paths to work properly. Raises werkzeug.exceptions.NotFound if the resulting path would fall out of the root directory.
normalize_subpath
python
joeyespo/grip
grip/readers.py
https://github.com/joeyespo/grip/blob/master/grip/readers.py
MIT
def readme_for(self, subpath): """ Returns the full path for the README file for the specified subpath, or the root filename if subpath is None. Raises ReadmeNotFoundError if a README for the specified subpath does not exist. Raises werkzeug.exceptions.NotFound if the r...
Returns the full path for the README file for the specified subpath, or the root filename if subpath is None. Raises ReadmeNotFoundError if a README for the specified subpath does not exist. Raises werkzeug.exceptions.NotFound if the resulting path would fall out of th...
readme_for
python
joeyespo/grip
grip/readers.py
https://github.com/joeyespo/grip/blob/master/grip/readers.py
MIT
def filename_for(self, subpath): """ Returns the relative filename for the specified subpath, or the root filename if subpath is None. Raises werkzeug.exceptions.NotFound if the resulting path would fall out of the root directory. """ try: filename = ...
Returns the relative filename for the specified subpath, or the root filename if subpath is None. Raises werkzeug.exceptions.NotFound if the resulting path would fall out of the root directory.
filename_for
python
joeyespo/grip
grip/readers.py
https://github.com/joeyespo/grip/blob/master/grip/readers.py
MIT
def is_binary(self, subpath=None): """ Gets whether the specified subpath is a supported binary file. """ mimetype = self.mimetype_for(subpath) return mimetype and not mimetype.startswith('text/')
Gets whether the specified subpath is a supported binary file.
is_binary
python
joeyespo/grip
grip/readers.py
https://github.com/joeyespo/grip/blob/master/grip/readers.py
MIT
def last_updated(self, subpath=None): """ Returns the time of the last modification of the Readme or specified subpath, or None if the file does not exist. The return value is a number giving the number of seconds since the epoch (see the time module). Raises werkzeug.e...
Returns the time of the last modification of the Readme or specified subpath, or None if the file does not exist. The return value is a number giving the number of seconds since the epoch (see the time module). Raises werkzeug.exceptions.NotFound if the resulting path ...
last_updated
python
joeyespo/grip
grip/readers.py
https://github.com/joeyespo/grip/blob/master/grip/readers.py
MIT
def read(self, subpath=None): """ Returns the UTF-8 content of the specified subpath. subpath is expected to already have been normalized. Raises ReadmeNotFoundError if a README for the specified subpath does not exist. Raises werkzeug.exceptions.NotFound if the result...
Returns the UTF-8 content of the specified subpath. subpath is expected to already have been normalized. Raises ReadmeNotFoundError if a README for the specified subpath does not exist. Raises werkzeug.exceptions.NotFound if the resulting path would fall out of the ro...
read
python
joeyespo/grip
grip/readers.py
https://github.com/joeyespo/grip/blob/master/grip/readers.py
MIT
def filename_for(self, subpath): """ Returns the display filename, or None if subpath is specified since subpaths are not supported for text readers. """ if subpath is not None: return None return self.display_filename
Returns the display filename, or None if subpath is specified since subpaths are not supported for text readers.
filename_for
python
joeyespo/grip
grip/readers.py
https://github.com/joeyespo/grip/blob/master/grip/readers.py
MIT
def read(self, subpath=None): """ Returns the UTF-8 Readme content. Raises ReadmeNotFoundError if subpath is specified since subpaths are not supported for text readers. """ if subpath is not None: raise ReadmeNotFoundError(subpath) return self.text
Returns the UTF-8 Readme content. Raises ReadmeNotFoundError if subpath is specified since subpaths are not supported for text readers.
read
python
joeyespo/grip
grip/readers.py
https://github.com/joeyespo/grip/blob/master/grip/readers.py
MIT
def read_stdin(self): """ Reads STDIN until the end of input and returns a unicode string. """ text = sys.stdin.read() # Decode the bytes returned from earlier Python STDIN implementations if sys.version_info[0] < 3 and text is not None: text = text.decode(sy...
Reads STDIN until the end of input and returns a unicode string.
read_stdin
python
joeyespo/grip
grip/readers.py
https://github.com/joeyespo/grip/blob/master/grip/readers.py
MIT
def render(self, text, auth=None): """ Renders the specified markdown content and embedded styles. Raises TypeError if text is not a Unicode string. Raises requests.HTTPError if the request fails. """ # Ensure text is Unicode expected = str if sys.version_info[0]...
Renders the specified markdown content and embedded styles. Raises TypeError if text is not a Unicode string. Raises requests.HTTPError if the request fails.
render
python
joeyespo/grip
grip/renderers.py
https://github.com/joeyespo/grip/blob/master/grip/renderers.py
MIT
def render(self, text, auth=None): """ Renders the specified markdown content and embedded styles. """ if markdown is None: import markdown if UrlizeExtension is None: from .mdx_urlize import UrlizeExtension return markdown.markdown(text, extension...
Renders the specified markdown content and embedded styles.
render
python
joeyespo/grip
grip/renderers.py
https://github.com/joeyespo/grip/blob/master/grip/renderers.py
MIT
def safe_join(directory, *pathnames): """Safely join zero or more untrusted path components to a base directory to avoid escaping the base directory. :param directory: The trusted base directory. :param pathnames: The untrusted path components relative to the base directory....
Safely join zero or more untrusted path components to a base directory to avoid escaping the base directory. :param directory: The trusted base directory. :param pathnames: The untrusted path components relative to the base directory. :return: A safe path.
safe_join
python
joeyespo/grip
grip/_compat.py
https://github.com/joeyespo/grip/blob/master/grip/_compat.py
MIT
def add_metaclass(metaclass): """Class decorator for creating a class with a metaclass.""" def wrapper(cls): orig_vars = cls.__dict__.copy() slots = orig_vars.get('__slots__') if slots is not None: if isinstance(slots, str): slots = [slots] for slo...
Class decorator for creating a class with a metaclass.
add_metaclass
python
joeyespo/grip
grip/vendor/six.py
https://github.com/joeyespo/grip/blob/master/grip/vendor/six.py
MIT
def test_exceptions(): """ Test that ReadmeNotFoundError behaves like FileNotFoundError on Python 3 and IOError on Python 2. """ assert str(ReadmeNotFoundError()) == 'README not found' assert (str(ReadmeNotFoundError('.')) == 'No README found at .') assert str(ReadmeNotFoundError('some/path'...
Test that ReadmeNotFoundError behaves like FileNotFoundError on Python 3 and IOError on Python 2.
test_exceptions
python
joeyespo/grip
tests/test_api.py
https://github.com/joeyespo/grip/blob/master/tests/test_api.py
MIT
def disable_torch_init(): """ Disable the redundant torch default initialization to accelerate model creation. """ import torch setattr(torch.nn.Linear, "reset_parameters", lambda self: None) setattr(torch.nn.LayerNorm, "reset_parameters", lambda self: None)
Disable the redundant torch default initialization to accelerate model creation.
disable_torch_init
python
PKU-YuanGroup/Chat-UniVi
ChatUniVi/utils.py
https://github.com/PKU-YuanGroup/Chat-UniVi/blob/master/ChatUniVi/utils.py
Apache-2.0
def violates_moderation(text): """ Check whether the text violates OpenAI moderation API. """ url = "https://api.openai.com/v1/moderations" headers = {"Content-Type": "application/json", "Authorization": "Bearer " + os.environ["OPENAI_API_KEY"]} text = text.replace("\n", "") d...
Check whether the text violates OpenAI moderation API.
violates_moderation
python
PKU-YuanGroup/Chat-UniVi
ChatUniVi/utils.py
https://github.com/PKU-YuanGroup/Chat-UniVi/blob/master/ChatUniVi/utils.py
Apache-2.0
def split_list(lst, n): """Split a list into n (roughly) equal-sized chunks""" chunk_size = math.ceil(len(lst) / n) # integer division return [lst[i:i+chunk_size] for i in range(0, len(lst), chunk_size)]
Split a list into n (roughly) equal-sized chunks
split_list
python
PKU-YuanGroup/Chat-UniVi
ChatUniVi/eval/model_coco_vqa.py
https://github.com/PKU-YuanGroup/Chat-UniVi/blob/master/ChatUniVi/eval/model_coco_vqa.py
Apache-2.0
def annotate(prediction_set, caption_files, output_dir): """ Evaluates question and answer pairs using GPT-3 Returns a score for correctness. """ for file in caption_files: key = file[:-5] # Strip file extension qa_set = prediction_set[key] question = qa_set['q'] answ...
Evaluates question and answer pairs using GPT-3 Returns a score for correctness.
annotate
python
PKU-YuanGroup/Chat-UniVi
ChatUniVi/eval/evaluate/evaluate_benchmark_1_correctness.py
https://github.com/PKU-YuanGroup/Chat-UniVi/blob/master/ChatUniVi/eval/evaluate/evaluate_benchmark_1_correctness.py
Apache-2.0
def main(): """ Main function to control the flow of the program. """ # Parse arguments. args = parse_args() file = args.pred_path try: pred_contents = json.load(file) except: pred_contents = read_jsonl(file) # Dictionary to store the count of occurrences for each v...
Main function to control the flow of the program.
main
python
PKU-YuanGroup/Chat-UniVi
ChatUniVi/eval/evaluate/evaluate_benchmark_1_correctness.py
https://github.com/PKU-YuanGroup/Chat-UniVi/blob/master/ChatUniVi/eval/evaluate/evaluate_benchmark_1_correctness.py
Apache-2.0
def annotate(prediction_set, caption_files, output_dir): """ Evaluates question and answer pairs using GPT-3 and returns a score for detailed orientation. """ for file in caption_files: key = file[:-5] # Strip file extension qa_set = prediction_set[key] question = qa_set['q']...
Evaluates question and answer pairs using GPT-3 and returns a score for detailed orientation.
annotate
python
PKU-YuanGroup/Chat-UniVi
ChatUniVi/eval/evaluate/evaluate_benchmark_2_detailed_orientation.py
https://github.com/PKU-YuanGroup/Chat-UniVi/blob/master/ChatUniVi/eval/evaluate/evaluate_benchmark_2_detailed_orientation.py
Apache-2.0
def annotate(prediction_set, caption_files, output_dir): """ Evaluates question and answer pairs using GPT-3 and returns a score for contextual understanding. """ for file in caption_files: key = file[:-5] # Strip file extension qa_set = prediction_set[key] question = qa_set[...
Evaluates question and answer pairs using GPT-3 and returns a score for contextual understanding.
annotate
python
PKU-YuanGroup/Chat-UniVi
ChatUniVi/eval/evaluate/evaluate_benchmark_3_context.py
https://github.com/PKU-YuanGroup/Chat-UniVi/blob/master/ChatUniVi/eval/evaluate/evaluate_benchmark_3_context.py
Apache-2.0
def annotate(prediction_set, caption_files, output_dir): """ Evaluates question and answer pairs using GPT-3 and returns a score for temporal understanding. """ for file in caption_files: key = file[:-5] # Strip file extension qa_set = prediction_set[key] question = qa_set['q...
Evaluates question and answer pairs using GPT-3 and returns a score for temporal understanding.
annotate
python
PKU-YuanGroup/Chat-UniVi
ChatUniVi/eval/evaluate/evaluate_benchmark_4_temporal.py
https://github.com/PKU-YuanGroup/Chat-UniVi/blob/master/ChatUniVi/eval/evaluate/evaluate_benchmark_4_temporal.py
Apache-2.0
def annotate(prediction_set, caption_files, output_dir): """ Evaluates question and answer pairs using GPT-3 and returns a score for consistency. """ for file in caption_files: key = file[:-5] # Strip file extension qa_set = prediction_set[key] question1 = qa_set['q1'] ...
Evaluates question and answer pairs using GPT-3 and returns a score for consistency.
annotate
python
PKU-YuanGroup/Chat-UniVi
ChatUniVi/eval/evaluate/evaluate_benchmark_5_consistency.py
https://github.com/PKU-YuanGroup/Chat-UniVi/blob/master/ChatUniVi/eval/evaluate/evaluate_benchmark_5_consistency.py
Apache-2.0
def get_pred_idx(prediction, choices, options): """ Get the index (e.g. 2) from the prediction (e.g. 'C') """ if prediction in options[:len(choices)]: return options.index(prediction) else: return random.choice(range(len(choices)))
Get the index (e.g. 2) from the prediction (e.g. 'C')
get_pred_idx
python
PKU-YuanGroup/Chat-UniVi
ChatUniVi/eval/evaluate/evaluate_science_qa.py
https://github.com/PKU-YuanGroup/Chat-UniVi/blob/master/ChatUniVi/eval/evaluate/evaluate_science_qa.py
Apache-2.0
def trunc_normal_(tensor, mean=0., std=1., a=-2., b=2.): # type: (Tensor, float, float, float, float) -> Tensor r"""Fills the input Tensor with values drawn from a truncated normal distribution. The values are effectively drawn from the normal distribution :math:`\mathcal{N}(\text{mean}, \text{std}^2)` ...
Fills the input Tensor with values drawn from a truncated normal distribution. The values are effectively drawn from the normal distribution :math:`\mathcal{N}(\text{mean}, \text{std}^2)` with values outside :math:`[a, b]` redrawn until they are within the bounds. The method used for generating the rand...
trunc_normal_
python
PKU-YuanGroup/Chat-UniVi
ChatUniVi/model/cluster.py
https://github.com/PKU-YuanGroup/Chat-UniVi/blob/master/ChatUniVi/model/cluster.py
Apache-2.0
def drop_path(x, drop_prob: float = 0., training: bool = False): """Drop paths (Stochastic Depth) per sample (when applied in main path of residual blocks). """ if drop_prob == 0. or not training: return x keep_prob = 1 - drop_prob shape = (x.shape[0],) + (1,) * (x.ndim - 1) # work with dif...
Drop paths (Stochastic Depth) per sample (when applied in main path of residual blocks).
drop_path
python
PKU-YuanGroup/Chat-UniVi
ChatUniVi/model/cluster.py
https://github.com/PKU-YuanGroup/Chat-UniVi/blob/master/ChatUniVi/model/cluster.py
Apache-2.0
def index_points(points, idx): """Sample features following the index. Returns: new_points:, indexed points data, [B, S, C] Args: points: input points data, [B, N, C] idx: sample index data, [B, S] """ device = points.device B = points.shape[0] view_shape = list(idx....
Sample features following the index. Returns: new_points:, indexed points data, [B, S, C] Args: points: input points data, [B, N, C] idx: sample index data, [B, S]
index_points
python
PKU-YuanGroup/Chat-UniVi
ChatUniVi/model/cluster.py
https://github.com/PKU-YuanGroup/Chat-UniVi/blob/master/ChatUniVi/model/cluster.py
Apache-2.0
def cluster_dpc_knn(token_dict, cluster_num, k=5, token_mask=None): """Cluster tokens with DPC-KNN algorithm. Return: idx_cluster (Tensor[B, N]): cluster index of each token. cluster_num (int): actual cluster number. The same with input cluster number Args: token_dict (di...
Cluster tokens with DPC-KNN algorithm. Return: idx_cluster (Tensor[B, N]): cluster index of each token. cluster_num (int): actual cluster number. The same with input cluster number Args: token_dict (dict): dict for token information cluster_num (int): cluster number ...
cluster_dpc_knn
python
PKU-YuanGroup/Chat-UniVi
ChatUniVi/model/cluster.py
https://github.com/PKU-YuanGroup/Chat-UniVi/blob/master/ChatUniVi/model/cluster.py
Apache-2.0
def merge_tokens(token_dict, idx_cluster, cluster_num, token_weight=None): """Merge tokens in the same cluster to a single cluster. Implemented by torch.index_add(). Flops: B*N*(C+2) Return: out_dict (dict): dict for output token information Args: token_dict (dict): dict for input token...
Merge tokens in the same cluster to a single cluster. Implemented by torch.index_add(). Flops: B*N*(C+2) Return: out_dict (dict): dict for output token information Args: token_dict (dict): dict for input token information idx_cluster (Tensor[B, N]): cluster index of each token. ...
merge_tokens
python
PKU-YuanGroup/Chat-UniVi
ChatUniVi/model/cluster.py
https://github.com/PKU-YuanGroup/Chat-UniVi/blob/master/ChatUniVi/model/cluster.py
Apache-2.0
def setup_for_distributed(is_master): """ This function disables printing when not in master process """ import builtins as __builtin__ builtin_print = __builtin__.print def print(*args, **kwargs): force = kwargs.pop("force", False) if is_master or force: builtin_pr...
This function disables printing when not in master process
setup_for_distributed
python
PKU-YuanGroup/Chat-UniVi
ChatUniVi/model/multimodal_encoder/utils.py
https://github.com/PKU-YuanGroup/Chat-UniVi/blob/master/ChatUniVi/model/multimodal_encoder/utils.py
Apache-2.0
def download_cached_file(url, check_hash=True, progress=False): """ Download a file from a URL and cache it locally. If the file already exists, it is not downloaded again. If distributed, only the main process downloads the file, and the other processes wait for the file to be downloaded. """ def ...
Download a file from a URL and cache it locally. If the file already exists, it is not downloaded again. If distributed, only the main process downloads the file, and the other processes wait for the file to be downloaded.
download_cached_file
python
PKU-YuanGroup/Chat-UniVi
ChatUniVi/model/multimodal_encoder/utils.py
https://github.com/PKU-YuanGroup/Chat-UniVi/blob/master/ChatUniVi/model/multimodal_encoder/utils.py
Apache-2.0
def forward( self, hidden_states: torch.Tensor, attention_mask: Optional[torch.Tensor] = None, position_ids: Optional[torch.Tensor] = None, past_key_value: Optional[Tuple[torch.Tensor]] = None, output_attentions: bool = False, use_cache: bool = False, ) -> Tuple[torch.Tensor, Optional[torch....
Input shape: Batch x Time x Channel attention_mask: [bsz, q_len]
forward
python
PKU-YuanGroup/Chat-UniVi
ChatUniVi/train/llama_flash_attn_monkey_patch.py
https://github.com/PKU-YuanGroup/Chat-UniVi/blob/master/ChatUniVi/train/llama_flash_attn_monkey_patch.py
Apache-2.0
def safe_save_model_for_hf_trainer(trainer: transformers.Trainer, output_dir: str): """Collects the state dict and dump to disk.""" if getattr(trainer.args, "tune_mm_mlp_adapter", False): # Only save Adapter keys_to_match = ['mm_projector', "ctm", "block"] ...
Collects the state dict and dump to disk.
safe_save_model_for_hf_trainer
python
PKU-YuanGroup/Chat-UniVi
ChatUniVi/train/train.py
https://github.com/PKU-YuanGroup/Chat-UniVi/blob/master/ChatUniVi/train/train.py
Apache-2.0
def smart_tokenizer_and_embedding_resize( special_tokens_dict: Dict, tokenizer: transformers.PreTrainedTokenizer, model: transformers.PreTrainedModel, ): """Resize tokenizer and embedding. Note: This is the unoptimized version that may make your embedding size not be divisible by 64. ...
Resize tokenizer and embedding. Note: This is the unoptimized version that may make your embedding size not be divisible by 64.
smart_tokenizer_and_embedding_resize
python
PKU-YuanGroup/Chat-UniVi
ChatUniVi/train/train.py
https://github.com/PKU-YuanGroup/Chat-UniVi/blob/master/ChatUniVi/train/train.py
Apache-2.0
def _add_speaker_and_signal(header, source, get_conversation=True): """Add speaker and start/end signal on each round.""" BEGIN_SIGNAL = "### " END_SIGNAL = "\n" conversation = header for sentence in source: from_str = sentence["from"] if from_str.lower() == "human": from...
Add speaker and start/end signal on each round.
_add_speaker_and_signal
python
PKU-YuanGroup/Chat-UniVi
ChatUniVi/train/train.py
https://github.com/PKU-YuanGroup/Chat-UniVi/blob/master/ChatUniVi/train/train.py
Apache-2.0
def preprocess( sources: Sequence[str], tokenizer: transformers.PreTrainedTokenizer, has_image: bool = False ) -> Dict: """ Given a list of sources, each is a conversation list. This transform: 1. Add signal '### ' at the beginning each sentence, with end signal '\n'; 2. Concaten...
Given a list of sources, each is a conversation list. This transform: 1. Add signal '### ' at the beginning each sentence, with end signal ' '; 2. Concatenate conversations together; 3. Tokenize the concatenated conversation; 4. Make a deepcopy as the target. Mask human words with IGNORE_INDEX. ...
preprocess
python
PKU-YuanGroup/Chat-UniVi
ChatUniVi/train/train.py
https://github.com/PKU-YuanGroup/Chat-UniVi/blob/master/ChatUniVi/train/train.py
Apache-2.0
def make_supervised_data_module(tokenizer: transformers.PreTrainedTokenizer, data_args) -> Dict: """Make dataset and collator for supervised fine-tuning.""" train_dataset = LazySupervisedDataset(tokenizer=tokenizer, data_args=data_args) data_collator = DataCollatorForSupervis...
Make dataset and collator for supervised fine-tuning.
make_supervised_data_module
python
PKU-YuanGroup/Chat-UniVi
ChatUniVi/train/train.py
https://github.com/PKU-YuanGroup/Chat-UniVi/blob/master/ChatUniVi/train/train.py
Apache-2.0
def command(self, command, *args): """ Issue a command to MPV. Will block until completed or timeout is reached. *command* is the name of the MPV command All further arguments are forwarded to the MPV command. Throws TimeoutError if timeout of 120 seconds is reached. ...
Issue a command to MPV. Will block until completed or timeout is reached. *command* is the name of the MPV command All further arguments are forwarded to the MPV command. Throws TimeoutError if timeout of 120 seconds is reached.
command
python
kjtsune/embyToLocalPlayer
utils/python_mpv_jsonipc.py
https://github.com/kjtsune/embyToLocalPlayer/blob/master/utils/python_mpv_jsonipc.py
Apache-2.0
def get_series_single_season(self, ser_id, season_num, translations='', info_only=False): """ ser_id: Trakt ID, Trakt slug, or IMDB ID translations: specific 2 digit country language code return: [{.., ids:ep_ids}, ..] not standard ids_item, not type field """ trans = f'?...
ser_id: Trakt ID, Trakt slug, or IMDB ID translations: specific 2 digit country language code return: [{.., ids:ep_ids}, ..] not standard ids_item, not type field
get_series_single_season
python
kjtsune/embyToLocalPlayer
utils/trakt_api.py
https://github.com/kjtsune/embyToLocalPlayer/blob/master/utils/trakt_api.py
Apache-2.0
async def math_guardrail( context: RunContextWrapper[None], agent: Agent, input: str | list[TResponseInputItem] ) -> GuardrailFunctionOutput: """This is an input guardrail function, which happens to call an agent to check if the input is a math homework question. """ result = await Runner.run(guardr...
This is an input guardrail function, which happens to call an agent to check if the input is a math homework question.
math_guardrail
python
openai/openai-agents-python
examples/agent_patterns/input_guardrails.py
https://github.com/openai/openai-agents-python/blob/master/examples/agent_patterns/input_guardrails.py
MIT
async def update_seat( context: RunContextWrapper[AirlineAgentContext], confirmation_number: str, new_seat: str ) -> str: """ Update the seat for a given confirmation number. Args: confirmation_number: The confirmation number for the flight. new_seat: The new seat to update to. """ ...
Update the seat for a given confirmation number. Args: confirmation_number: The confirmation number for the flight. new_seat: The new seat to update to.
update_seat
python
openai/openai-agents-python
examples/customer_service/main.py
https://github.com/openai/openai-agents-python/blob/master/examples/customer_service/main.py
MIT
def get_weather(city: str) -> str: """Get the weather for a given city.""" print(f"[debug] get_weather called with city: {city}") choices = ["sunny", "cloudy", "rainy", "snowy"] return f"The weather in {city} is {random.choice(choices)}."
Get the weather for a given city.
get_weather
python
openai/openai-agents-python
examples/voice/static/main.py
https://github.com/openai/openai-agents-python/blob/master/examples/voice/static/main.py
MIT
def compose(self) -> ComposeResult: """Create child widgets for the app.""" with Container(): yield Header(id="session-display") yield AudioStatusIndicator(id="status-indicator") yield RichLog(id="bottom-pane", wrap=True, highlight=True, markup=True)
Create child widgets for the app.
compose
python
openai/openai-agents-python
examples/voice/streamed/main.py
https://github.com/openai/openai-agents-python/blob/master/examples/voice/streamed/main.py
MIT
def __init__(self, secret_word: str, on_start: Callable[[str], None]): """ Args: secret_word: The secret word to guess. on_start: A callback that is called when the workflow starts. The transcription is passed in as an argument. """ self._input_his...
Args: secret_word: The secret word to guess. on_start: A callback that is called when the workflow starts. The transcription is passed in as an argument.
__init__
python
openai/openai-agents-python
examples/voice/streamed/my_workflow.py
https://github.com/openai/openai-agents-python/blob/master/examples/voice/streamed/my_workflow.py
MIT
def as_tool( self, tool_name: str | None, tool_description: str | None, custom_output_extractor: Callable[[RunResult], Awaitable[str]] | None = None, ) -> Tool: """Transform this agent into a tool, callable by other agents. This is different from handoffs in two ways...
Transform this agent into a tool, callable by other agents. This is different from handoffs in two ways: 1. In handoffs, the new agent receives the conversation history. In this tool, the new agent receives generated input. 2. In handoffs, the new agent takes over the conversation. I...
as_tool
python
openai/openai-agents-python
src/agents/agent.py
https://github.com/openai/openai-agents-python/blob/master/src/agents/agent.py
MIT
async def get_system_prompt(self, run_context: RunContextWrapper[TContext]) -> str | None: """Get the system prompt for the agent.""" if isinstance(self.instructions, str): return self.instructions elif callable(self.instructions): if inspect.iscoroutinefunction(self.inst...
Get the system prompt for the agent.
get_system_prompt
python
openai/openai-agents-python
src/agents/agent.py
https://github.com/openai/openai-agents-python/blob/master/src/agents/agent.py
MIT
async def get_mcp_tools(self) -> list[Tool]: """Fetches the available tools from the MCP servers.""" convert_schemas_to_strict = self.mcp_config.get("convert_schemas_to_strict", False) return await MCPUtil.get_all_function_tools(self.mcp_servers, convert_schemas_to_strict)
Fetches the available tools from the MCP servers.
get_mcp_tools
python
openai/openai-agents-python
src/agents/agent.py
https://github.com/openai/openai-agents-python/blob/master/src/agents/agent.py
MIT
async def get_all_tools(self, run_context: RunContextWrapper[Any]) -> list[Tool]: """All agent tools, including MCP tools and function tools.""" mcp_tools = await self.get_mcp_tools() async def _check_tool_enabled(tool: Tool) -> bool: if not isinstance(tool, FunctionTool): ...
All agent tools, including MCP tools and function tools.
get_all_tools
python
openai/openai-agents-python
src/agents/agent.py
https://github.com/openai/openai-agents-python/blob/master/src/agents/agent.py
MIT
def __init__(self, output_type: type[Any], strict_json_schema: bool = True): """ Args: output_type: The type of the output. strict_json_schema: Whether the JSON schema is in strict mode. We **strongly** recommend setting this to True, as it increases the likelihoo...
Args: output_type: The type of the output. strict_json_schema: Whether the JSON schema is in strict mode. We **strongly** recommend setting this to True, as it increases the likelihood of correct JSON input.
__init__
python
openai/openai-agents-python
src/agents/agent_output.py
https://github.com/openai/openai-agents-python/blob/master/src/agents/agent_output.py
MIT
def json_schema(self) -> dict[str, Any]: """The JSON schema of the output type.""" if self.is_plain_text(): raise UserError("Output type is plain text, so no JSON schema is available") return self._output_schema
The JSON schema of the output type.
json_schema
python
openai/openai-agents-python
src/agents/agent_output.py
https://github.com/openai/openai-agents-python/blob/master/src/agents/agent_output.py
MIT
def validate_json(self, json_str: str) -> Any: """Validate a JSON string against the output type. Returns the validated object, or raises a `ModelBehaviorError` if the JSON is invalid. """ validated = _json.validate_json(json_str, self._type_adapter, partial=False) if self._is_wr...
Validate a JSON string against the output type. Returns the validated object, or raises a `ModelBehaviorError` if the JSON is invalid.
validate_json
python
openai/openai-agents-python
src/agents/agent_output.py
https://github.com/openai/openai-agents-python/blob/master/src/agents/agent_output.py
MIT
def to_call_args(self, data: BaseModel) -> tuple[list[Any], dict[str, Any]]: """ Converts validated data from the Pydantic model into (args, kwargs), suitable for calling the original function. """ positional_args: list[Any] = [] keyword_args: dict[str, Any] = {} ...
Converts validated data from the Pydantic model into (args, kwargs), suitable for calling the original function.
to_call_args
python
openai/openai-agents-python
src/agents/function_schema.py
https://github.com/openai/openai-agents-python/blob/master/src/agents/function_schema.py
MIT
def generate_func_documentation( func: Callable[..., Any], style: DocstringStyle | None = None ) -> FuncDocumentation: """ Extracts metadata from a function docstring, in preparation for sending it to an LLM as a tool. Args: func: The function to extract documentation from. style: The s...
Extracts metadata from a function docstring, in preparation for sending it to an LLM as a tool. Args: func: The function to extract documentation from. style: The style of the docstring to use for parsing. If not provided, we will attempt to auto-detect the style. Returns: ...
generate_func_documentation
python
openai/openai-agents-python
src/agents/function_schema.py
https://github.com/openai/openai-agents-python/blob/master/src/agents/function_schema.py
MIT
def function_schema( func: Callable[..., Any], docstring_style: DocstringStyle | None = None, name_override: str | None = None, description_override: str | None = None, use_docstring_info: bool = True, strict_json_schema: bool = True, ) -> FuncSchema: """ Given a python function, extract...
Given a python function, extracts a `FuncSchema` from it, capturing the name, description, parameter descriptions, and other metadata. Args: func: The function to extract the schema from. docstring_style: The style of the docstring to use for parsing. If not provided, we will a...
function_schema
python
openai/openai-agents-python
src/agents/function_schema.py
https://github.com/openai/openai-agents-python/blob/master/src/agents/function_schema.py
MIT
def input_guardrail( func: _InputGuardrailFuncSync[TContext_co] | _InputGuardrailFuncAsync[TContext_co] | None = None, *, name: str | None = None, ) -> ( InputGuardrail[TContext_co] | Callable[ [_InputGuardrailFuncSync[TContext_co] | _InputGuardrailFuncAsync[TContext_co]], In...
Decorator that transforms a sync or async function into an `InputGuardrail`. It can be used directly (no parentheses) or with keyword args, e.g.: @input_guardrail def my_sync_guardrail(...): ... @input_guardrail(name="guardrail_name") async def my_async_guardrail(...): ... ...
input_guardrail
python
openai/openai-agents-python
src/agents/guardrail.py
https://github.com/openai/openai-agents-python/blob/master/src/agents/guardrail.py
MIT
def output_guardrail( func: _OutputGuardrailFuncSync[TContext_co] | _OutputGuardrailFuncAsync[TContext_co] | None = None, *, name: str | None = None, ) -> ( OutputGuardrail[TContext_co] | Callable[ [_OutputGuardrailFuncSync[TContext_co] | _OutputGuardrailFuncAsync[TContext_co]], ...
Decorator that transforms a sync or async function into an `OutputGuardrail`. It can be used directly (no parentheses) or with keyword args, e.g.: @output_guardrail def my_sync_guardrail(...): ... @output_guardrail(name="guardrail_name") async def my_async_guardrail(...): ... ...
output_guardrail
python
openai/openai-agents-python
src/agents/guardrail.py
https://github.com/openai/openai-agents-python/blob/master/src/agents/guardrail.py
MIT
def handoff( agent: Agent[TContext], tool_name_override: str | None = None, tool_description_override: str | None = None, on_handoff: OnHandoffWithInput[THandoffInput] | OnHandoffWithoutInput | None = None, input_type: type[THandoffInput] | None = None, input_filter: Callable[[HandoffInputData],...
Create a handoff from an agent. Args: agent: The agent to handoff to, or a function that returns an agent. tool_name_override: Optional override for the name of the tool that represents the handoff. tool_description_override: Optional override for the description of the tool that ...
handoff
python
openai/openai-agents-python
src/agents/handoffs.py
https://github.com/openai/openai-agents-python/blob/master/src/agents/handoffs.py
MIT
def to_input_item(self) -> TResponseInputItem: """Converts this item into an input item suitable for passing to the model.""" if isinstance(self.raw_item, dict): # We know that input items are dicts, so we can ignore the type error return self.raw_item # type: ignore eli...
Converts this item into an input item suitable for passing to the model.
to_input_item
python
openai/openai-agents-python
src/agents/items.py
https://github.com/openai/openai-agents-python/blob/master/src/agents/items.py
MIT
def to_input_items(self) -> list[TResponseInputItem]: """Convert the output into a list of input items suitable for passing to the model.""" # We happen to know that the shape of the Pydantic output items are the same as the # equivalent TypedDict input items, so we can just convert each one. ...
Convert the output into a list of input items suitable for passing to the model.
to_input_items
python
openai/openai-agents-python
src/agents/items.py
https://github.com/openai/openai-agents-python/blob/master/src/agents/items.py
MIT
def extract_last_content(cls, message: TResponseOutputItem) -> str: """Extracts the last text content or refusal from a message.""" if not isinstance(message, ResponseOutputMessage): return "" last_content = message.content[-1] if isinstance(last_content, ResponseOutputText)...
Extracts the last text content or refusal from a message.
extract_last_content
python
openai/openai-agents-python
src/agents/items.py
https://github.com/openai/openai-agents-python/blob/master/src/agents/items.py
MIT
def extract_last_text(cls, message: TResponseOutputItem) -> str | None: """Extracts the last text content from a message, if any. Ignores refusals.""" if isinstance(message, ResponseOutputMessage): last_content = message.content[-1] if isinstance(last_content, ResponseOutputText)...
Extracts the last text content from a message, if any. Ignores refusals.
extract_last_text
python
openai/openai-agents-python
src/agents/items.py
https://github.com/openai/openai-agents-python/blob/master/src/agents/items.py
MIT
def input_to_new_input_list( cls, input: str | list[TResponseInputItem] ) -> list[TResponseInputItem]: """Converts a string or list of input items into a list of input items.""" if isinstance(input, str): return [ { "content": input, ...
Converts a string or list of input items into a list of input items.
input_to_new_input_list
python
openai/openai-agents-python
src/agents/items.py
https://github.com/openai/openai-agents-python/blob/master/src/agents/items.py
MIT
def text_message_outputs(cls, items: list[RunItem]) -> str: """Concatenates all the text content from a list of message output items.""" text = "" for item in items: if isinstance(item, MessageOutputItem): text += cls.text_message_output(item) return text
Concatenates all the text content from a list of message output items.
text_message_outputs
python
openai/openai-agents-python
src/agents/items.py
https://github.com/openai/openai-agents-python/blob/master/src/agents/items.py
MIT
def text_message_output(cls, message: MessageOutputItem) -> str: """Extracts all the text content from a single message output item.""" text = "" for item in message.raw_item.content: if isinstance(item, ResponseOutputText): text += item.text return text
Extracts all the text content from a single message output item.
text_message_output
python
openai/openai-agents-python
src/agents/items.py
https://github.com/openai/openai-agents-python/blob/master/src/agents/items.py
MIT
def tool_call_output_item( cls, tool_call: ResponseFunctionToolCall, output: str ) -> FunctionCallOutput: """Creates a tool call output item from a tool call and its output.""" return { "call_id": tool_call.call_id, "output": output, "type": "function_call...
Creates a tool call output item from a tool call and its output.
tool_call_output_item
python
openai/openai-agents-python
src/agents/items.py
https://github.com/openai/openai-agents-python/blob/master/src/agents/items.py
MIT
async def on_agent_start( self, context: RunContextWrapper[TContext], agent: Agent[TContext] ) -> None: """Called before the agent is invoked. Called each time the current agent changes.""" pass
Called before the agent is invoked. Called each time the current agent changes.
on_agent_start
python
openai/openai-agents-python
src/agents/lifecycle.py
https://github.com/openai/openai-agents-python/blob/master/src/agents/lifecycle.py
MIT
async def on_agent_end( self, context: RunContextWrapper[TContext], agent: Agent[TContext], output: Any, ) -> None: """Called when the agent produces a final output.""" pass
Called when the agent produces a final output.
on_agent_end
python
openai/openai-agents-python
src/agents/lifecycle.py
https://github.com/openai/openai-agents-python/blob/master/src/agents/lifecycle.py
MIT
async def on_start(self, context: RunContextWrapper[TContext], agent: Agent[TContext]) -> None: """Called before the agent is invoked. Called each time the running agent is changed to this agent.""" pass
Called before the agent is invoked. Called each time the running agent is changed to this agent.
on_start
python
openai/openai-agents-python
src/agents/lifecycle.py
https://github.com/openai/openai-agents-python/blob/master/src/agents/lifecycle.py
MIT
async def on_handoff( self, context: RunContextWrapper[TContext], agent: Agent[TContext], source: Agent[TContext], ) -> None: """Called when the agent is being handed off to. The `source` is the agent that is handing off to this agent.""" pass
Called when the agent is being handed off to. The `source` is the agent that is handing off to this agent.
on_handoff
python
openai/openai-agents-python
src/agents/lifecycle.py
https://github.com/openai/openai-agents-python/blob/master/src/agents/lifecycle.py
MIT
def resolve(self, override: ModelSettings | None) -> ModelSettings: """Produce a new ModelSettings by overlaying any non-None values from the override on top of this instance.""" if override is None: return self changes = { field.name: getattr(override, field.nam...
Produce a new ModelSettings by overlaying any non-None values from the override on top of this instance.
resolve
python
openai/openai-agents-python
src/agents/model_settings.py
https://github.com/openai/openai-agents-python/blob/master/src/agents/model_settings.py
MIT
async def run_demo_loop(agent: Agent[Any], *, stream: bool = True) -> None: """Run a simple REPL loop with the given agent. This utility allows quick manual testing and debugging of an agent from the command line. Conversation state is preserved across turns. Enter ``exit`` or ``quit`` to stop the loop...
Run a simple REPL loop with the given agent. This utility allows quick manual testing and debugging of an agent from the command line. Conversation state is preserved across turns. Enter ``exit`` or ``quit`` to stop the loop. Args: agent: The starting agent to run. stream: Whether to s...
run_demo_loop
python
openai/openai-agents-python
src/agents/repl.py
https://github.com/openai/openai-agents-python/blob/master/src/agents/repl.py
MIT
def final_output_as(self, cls: type[T], raise_if_incorrect_type: bool = False) -> T: """A convenience method to cast the final output to a specific type. By default, the cast is only for the typechecker. If you set `raise_if_incorrect_type` to True, we'll raise a TypeError if the final output is...
A convenience method to cast the final output to a specific type. By default, the cast is only for the typechecker. If you set `raise_if_incorrect_type` to True, we'll raise a TypeError if the final output is not of the given type. Args: cls: The type to cast the final output to. ...
final_output_as
python
openai/openai-agents-python
src/agents/result.py
https://github.com/openai/openai-agents-python/blob/master/src/agents/result.py
MIT
def to_input_list(self) -> list[TResponseInputItem]: """Creates a new input list, merging the original input with all the new items generated.""" original_items: list[TResponseInputItem] = ItemHelpers.input_to_new_input_list(self.input) new_items = [item.to_input_item() for item in self.new_item...
Creates a new input list, merging the original input with all the new items generated.
to_input_list
python
openai/openai-agents-python
src/agents/result.py
https://github.com/openai/openai-agents-python/blob/master/src/agents/result.py
MIT
def last_response_id(self) -> str | None: """Convenience method to get the response ID of the last model response.""" if not self.raw_responses: return None return self.raw_responses[-1].response_id
Convenience method to get the response ID of the last model response.
last_response_id
python
openai/openai-agents-python
src/agents/result.py
https://github.com/openai/openai-agents-python/blob/master/src/agents/result.py
MIT
def cancel(self) -> None: """Cancels the streaming run, stopping all background tasks and marking the run as complete.""" self._cleanup_tasks() # Cancel all running tasks self.is_complete = True # Mark the run as complete to stop event streaming # Optionally, clear the event q...
Cancels the streaming run, stopping all background tasks and marking the run as complete.
cancel
python
openai/openai-agents-python
src/agents/result.py
https://github.com/openai/openai-agents-python/blob/master/src/agents/result.py
MIT
def _create_error_details(self) -> RunErrorDetails: """Return a `RunErrorDetails` object considering the current attributes of the class.""" return RunErrorDetails( input=self.input, new_items=self.new_items, raw_responses=self.raw_responses, last_agent=se...
Return a `RunErrorDetails` object considering the current attributes of the class.
_create_error_details
python
openai/openai-agents-python
src/agents/result.py
https://github.com/openai/openai-agents-python/blob/master/src/agents/result.py
MIT
async def run( cls, starting_agent: Agent[TContext], input: str | list[TResponseInputItem], *, context: TContext | None = None, max_turns: int = DEFAULT_MAX_TURNS, hooks: RunHooks[TContext] | None = None, run_config: RunConfig | None = None, previo...
Run a workflow starting at the given agent. The agent will run in a loop until a final output is generated. The loop runs like so: 1. The agent is invoked with the given input. 2. If there is a final output (i.e. the agent produces something of type `agent.output_type`, the loop term...
run
python
openai/openai-agents-python
src/agents/run.py
https://github.com/openai/openai-agents-python/blob/master/src/agents/run.py
MIT