# Cache

## `autogen.Cache`

```python
Cache(config)
```

Bases: `AbstractCache`

A wrapper class for managing cache configuration and instances.

This class provides a unified interface for creating and interacting with different types of cache (e.g., Redis, Disk). It abstracts the underlying cache implementation details, providing methods for cache operations.

| ATTRIBUTE | DESCRIPTION |
| --- | --- |
| `config` | A dictionary containing cache configuration.<br>**TYPE:** `Dict[str, Any]` |
| `cache` | The cache instance created based on the provided configuration. |

Initialize the Cache with the given configuration.

Validates the configuration keys and creates the cache instance.

| PARAMETER | DESCRIPTION |
| --- | --- |
| `config` | A dictionary containing the cache configuration.<br>**TYPE:** `Dict[str, Any]` |

| RAISES | DESCRIPTION |
| --- | --- |
| `ValueError` | If an invalid configuration key is provided. |

Source code in `autogen/cache/cache.py`

```python
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
```

```python
def __init__(self, config: dict[str, Any]):
    """Initialize the Cache with the given configuration.
    Validates the configuration keys and creates the cache instance.
    Args:
        config (Dict[str, Any]): A dictionary containing the cache configuration.
    Raises:
        ValueError: If an invalid configuration key is provided.
    """
    self.config = config
    # Ensure that the seed is always treated as a string before being passed to any cache factory or stored.
    self.config["cache_seed"] = str(self.config.get("cache_seed", 42))
    # validate config
    for key in self.config:
        if key not in self.ALLOWED_CONFIG_KEYS:
            raise ValueError(f"Invalid config key: {key}")
    # create cache instance
    self.cache = CacheFactory.cache_factory(
        seed=self.config["cache_seed"],
        redis_url=self.config.get("redis_url"),
        cache_path_root=self.config.get("cache_path_root"),
        cosmosdb_config=self.config.get("cosmos_db_config"),
    )
```

### `ALLOWED_CONFIG_KEYS`

```python
ALLOWED_CONFIG_KEYS = ['cache_seed', 'redis_url', 'cache_path_root', 'cosmos_db_config']
```

### `config`

```python
config = config
```

### `cache`

```python
cache = cache_factory(seed=config['cache_seed'], redis_url=get('redis_url'), cache_path_root=get('cache_path_root'), cosmosdb_config=get('cosmos_db_config'))
```

### `redis`

```python
redis(cache_seed=42, redis_url='redis://localhost:6379/0')
```

Create a Redis cache instance.

| PARAMETER | DESCRIPTION |
| --- | --- |
| `cache_seed` | A seed for the cache. Defaults to 42.<br>**TYPE:** `Union[str, int]` **DEFAULT:** `42` |
| `redis_url` | The URL for the Redis server. Defaults to "redis://localhost:6379/0".<br>**TYPE:** `str` **DEFAULT:** `'redis://localhost:6379/0'` |

| RETURNS | DESCRIPTION |
| --- | --- |
| `Cache` | A Cache instance configured for Redis.<br>**TYPE:** `Cache` |

Source code in `autogen/cache/cache.py`

```python
@staticmethod

def redis(cache_seed: str | int = 42, redis_url: str = "redis://localhost:6379/0") -> Cache:
    """Create a Redis cache instance.
    Args:
        cache_seed (Union[str, int], optional): A seed for the cache. Defaults to 42.
        redis_url (str, optional): The URL for the Redis server. Defaults to "redis://localhost:6379/0".
    Returns:
        Cache: A Cache instance configured for Redis.
    """
    return Cache({"cache_seed": cache_seed, "redis_url": redis_url})
```

### `disk`

```python
disk(cache_seed=42, cache_path_root='.cache')
```

Create a Disk cache instance.

| PARAMETER | DESCRIPTION |
| --- | --- |
| `cache_seed` | A seed for the cache. Defaults to 42.<br>**TYPE:** `Union[str, int]` **DEFAULT:** `42` |
| `cache_path_root` | The root path for the disk cache. Defaults to ".cache".<br>**TYPE:** `str` **DEFAULT:** `'.cache'` |

| RETURNS | DESCRIPTION |
| --- | --- |
| `Cache` | A Cache instance configured for Disk caching.<br>**TYPE:** `Cache` |

Source code in `autogen/cache/cache.py`

```python
@staticmethod

def disk(cache_seed: str | int = 42, cache_path_root: str = ".cache") -> Cache:
    """Create a Disk cache instance.
    Args:
        cache_seed (Union[str, int], optional): A seed for the cache. Defaults to 42.
        cache_path_root (str, optional): The root path for the disk cache. Defaults to ".cache".
    Returns:
        Cache: A Cache instance configured for Disk caching.
    """
    return Cache({"cache_seed": cache_seed, "cache_path_root": cache_path_root})
```

### `cosmos_db`

```python
cosmos_db(connection_string=None, container_id=None, cache_seed=42, client=None)
```

Create a Cosmos DB cache instance with 'autogen_cache' as database ID.

| PARAMETER | DESCRIPTION |
| --- | --- |
| `connection_string` | Connection string to the Cosmos DB account.<br>**TYPE:** `str` **DEFAULT:** `None` |
| `container_id` | The container ID for the Cosmos DB account.<br>**TYPE:** `str` **DEFAULT:** `None` |
| `cache_seed` | A seed for the cache.<br>**TYPE:** `Union[str, int]` **DEFAULT:** `42` |
| `client` | Optional[CosmosClient]: Pass an existing Cosmos DB client.<br>**TYPE:** `Any | None` **DEFAULT:** `None` |

| RETURNS | DESCRIPTION |
| --- | --- |
| `Cache` | A Cache instance configured for Cosmos DB.<br>**TYPE:** `Cache` |

Source code in `autogen/cache/cache.py`

```python
@staticmethod

def cosmos_db(
    connection_string: str | None = None,
    container_id: str | None = None,
    cache_seed: str | int = 42,
    client: Any | None = None,
) -> Cache:
    """Create a Cosmos DB cache instance with 'autogen_cache' as database ID.
    Args:
        connection_string (str, optional): Connection string to the Cosmos DB account.
        container_id (str, optional): The container ID for the Cosmos DB account.
        cache_seed (Union[str, int], optional): A seed for the cache.
        client: Optional[CosmosClient]: Pass an existing Cosmos DB client.
    Returns:
        Cache: A Cache instance configured for Cosmos DB.
    """
    cosmos_db_config = {
        "connection_string": connection_string,
        "database_id": "autogen_cache",
        "container_id": container_id,
        "client": client,
    }
    return Cache({"cache_seed": str(cache_seed), "cosmos_db_config": cosmos_db_config})
```

### `get`

```python
get(key, default=None)
```

Retrieve an item from the cache.

| PARAMETER | DESCRIPTION |
| --- | --- |
| `key` | The key identifying the item in the cache.<br>**TYPE:** `str` |
| `default` | The default value to return if the key is not found. Defaults to None.<br>**TYPE:** `optional` **DEFAULT:** `None` |

| RETURNS | DESCRIPTION |
| --- | --- |
| `Any | None` | The value associated with the key if found, else the default value. |

Source code in `autogen/cache/cache.py`

```python
def get(self, key: str, default: Any | None = None) -> Any | None:
    """Retrieve an item from the cache.
    Args:
        key (str): The key identifying the item in the cache.
        default (optional): The default value to return if the key is not found.
                        Defaults to None.
    Returns:
        The value associated with the key if found, else the default value.
    """
    return self.cache.get(key, default)
```

### `set`

```python
set(key, value)
```

Set an item in the cache.

| PARAMETER | DESCRIPTION |
| --- | --- |
| `key` | The key under which the item is to be stored.<br>**TYPE:** `str` |
| `value` | The value to be stored in the cache.<br>**TYPE:** `Any` |

Source code in `autogen/cache/cache.py`

```python
def set(self, key: str, value: Any) -> None:
    """Set an item in the cache.
    Args:
        key (str): The key under which the item is to be stored.
        value: The value to be stored in the cache.
    """
    self.cache.set(key, value)
```

### `close`

```python
close()
```

Close the cache.

Perform any necessary cleanup, such as closing connections or releasing resources.

Source code in `autogen/cache/cache.py`

```python
def close(self) -> None:
    """Close the cache.
    Perform any necessary cleanup, such as closing connections or releasing resources.
    """
    self.cache.close()
```

### `get_current_cache`

```python
get_current_cache(cache=None)
```

Get the current cache instance.

| RETURNS | DESCRIPTION |
| --- | --- |
| `Cache` | The current cache instance.<br>**TYPE:** `Cache | None` |

Source code in `autogen/cache/cache.py`

```python
@classmethod
def get_current_cache(cls, cache: Cache | None = None) -> Cache | None:
    """Get the current cache instance.
    Returns:
        Cache: The current cache instance.
    """
    if cache is not None:
        return cache
    try:
        return cls._current_cache.get()
    except LookupError:
        return None
```
