You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
This pull request introduces two new utility helpers, a retry mechanism and an LRU-ish cache, located in the demo directory. These are provided primarily to showcase capabilities related to documentation generation but can also serve as foundational components for future features or internal tools.
demo/docs_demo.py Updates
This PR adds a new file, demo/docs_demo.py, which includes two general-purpose utilities: a retry function for robust operation execution and a Cache class for in-memory caching. These components are currently located in the demo directory, indicating their experimental or demonstration status.
Usage and Purpose
These utilities are designed to address common programming patterns for improving reliability and performance:
The retry function allows for automatically re-attempting a function call a specified number of times, with configurable delays and backoff, to handle transient failures.
The Cache class provides a simple in-memory key-value store with a limited size, employing a basic Least Recently Used (LRU)-like eviction strategy to manage its capacity.
As these are in the demo directory, they are suitable for experimentation and may be integrated into the main project or moved to a dedicated utils module in the future, following further review and enhancement.
Examples
Using the retry function
importrandomimporttimefromdemo.docs_demoimportretry# Assuming appropriate import pathdefunreliable_operation():
"""Simulates an operation that might fail randomly."""ifrandom.random() <0.7: # 70% chance of failureraiseValueError("Operation failed temporarily!")
return"Operation successful!"# Retry the unreliable_operation up to 5 times with a 1-second initial delay, doubling each time.try:
result=retry(unreliable_operation, attempts=5, base_delay=1.0, backoff=2.0, exceptions=(ValueError,))
print(f"Retry succeeded: {result}")
exceptExceptionase:
print(f"Retry failed after all attempts: {e}")
# Example of a function that will always succeed on the first trydefalways_succeed():
print("Always successful!")
return"Instant Success!"result_success=retry(always_succeed, attempts=3)
print(f"Immediate success: {result_success}")
Using the Cache class
fromdemo.docs_demoimportCache# Assuming appropriate import path# Initialize a cache with a max size of 2my_cache=Cache(max_size=2)
print(f"Cache size: {len(my_cache._store)}") # Current items: 0my_cache.put("key1", "value1")
my_cache.put("key2", "value2")
print(f"Cache after adding 2 items: {my_cache._store}")
# Expected: {'key1': 'value1', 'key2': 'value2'}print(f"Order: {my_cache._order}")
# Expected: ['key1', 'key2']# Accessing an itemprint(f"Get key1: {my_cache.get('key1')}")
# Expected: 'value1'# Adding a new item when cache is full will evict the oldest (key1 in this case)my_cache.put("key3", "value3")
print(f"Cache after adding key3 (key1 evicted): {my_cache._store}")
# Expected: {'key2': 'value2', 'key3': 'value3'}print(f"Order: {my_cache._order}")
# Expected: ['key2', 'key3']# Updating an existing item moves it to the end of the eviction ordermy_cache.put("key2", "updated_value2")
print(f"Cache after updating key2: {my_cache._store}")
# Expected: {'key2': 'updated_value2', 'key3': 'value3'}print(f"Order: {my_cache._order}")
# Expected: ['key3', 'key2'] # key2 moved to end as most recently 'put'
Executes a given function fn, retrying it up to a specified number of attempts if it raises an exception from a defined set.
This function is useful for handling operations that might fail due to transient issues, such as network timeouts, temporary resource unavailability, or database contention. It incorporates an exponential backoff strategy to reduce the load on the failing service during retries.
Parameters
fn (callable): The function to be executed and potentially retried. This function should take no arguments. If fn requires arguments, consider wrapping it in a lambda or functools.partial.
attempts (int, optional): The maximum number of times to attempt calling fn. Must be a positive integer. Defaults to 3.
base_delay (float, optional): The initial delay in seconds before the first retry. Defaults to 0.5.
backoff (float, optional): The factor by which the delay increases between successive retries. A value of 2.0 means the delay doubles each time. Defaults to 2.0.
exceptions (tuple or type, optional): A single exception type or a tuple of exception types that should trigger a retry. Any other exception type will be re-raised immediately. Defaults to (Exception,), meaning all exceptions will trigger a retry.
Returns
The result of the successful execution of fn.
Side Effects
May pause execution using time.sleep() between retry attempts.
If fn raises an exception not listed in exceptions, or if all attempts fail, the last encountered exception is re-raised.
Raises
The last exception caught during the retry loop if all attempts are exhausted.
class Cache
A simple, in-memory key-value cache with a fixed maximum size and an LRU-ish eviction policy.
This cache is suitable for storing frequently accessed data to reduce computational load or I/O operations, provided the data can fit within the specified max_size. The eviction policy prioritizes items that have been least recently put into the cache when new items need to be stored and the cache is full.
__init__(self, max_size=128)
Initializes a new Cache instance.
Parameters
max_size (int, optional): The maximum number of key-value pairs the cache can hold. Must be a positive integer. Defaults to 128.
get(self, key)
Retrieves the value associated with the given key from the cache.
Parameters
key (Hashable): The key of the item to retrieve.
Returns
The value associated with the key if found, otherwise None.
put(self, key, value)
Stores a value associated with a key in the cache.
If the cache is full (len(self._store) >= self.max_size) and the key is not already present, the least recently put item (based on insertion order tracking) will be evicted to make room for the new item. If the key already exists, its value is updated, and its position is moved to the "most recently put" end of the eviction order.
Parameters
key (Hashable): The key for the item to store.
value (Any): The value to store.
Returns
None.
Side Effects
Adds or updates an entry in the cache.
May evict an existing entry if the cache is at its max_size and a new key is being added.
Migration or Upgrade Notes
This pull request introduces new files and features in the demo directory. There are no breaking changes or modifications to existing core functionalities, so no specific migration or upgrade steps are required for existing users. These utilities are new additions and can be integrated into existing projects at discretion.
This is an AI-generated documentation draft. Please review, edit, and commit changes as appropriate.
Response generated using gemini-2.5-flash
dvirdung
changed the title
Demo: aido docs (v1.3.2)
Demo: aido docs
Jul 22, 2026
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Undocumented retry + LRU-ish cache helpers to showcase
aido docs— drafting docstrings, parameters, and usage notes. Commentaido docs. Part of the Aido demo set.