index
int64 0
731k
| package
stringlengths 2
98
⌀ | name
stringlengths 1
76
| docstring
stringlengths 0
281k
⌀ | code
stringlengths 4
1.07M
⌀ | signature
stringlengths 2
42.8k
⌀ |
---|---|---|---|---|---|
730,336 | mmengine.fileio.handlers.registry_utils | register_handler | null | def register_handler(file_formats, **kwargs):
def wrap(cls):
_register_handler(cls(**kwargs), file_formats)
return cls
return wrap
| (file_formats, **kwargs) |
730,338 | mmengine.fileio.io | remove | Remove a file.
Args:
filepath (str, Path): Path to be removed.
backend_args (dict, optional): Arguments to instantiate the
corresponding backend. Defaults to None.
Raises:
FileNotFoundError: If filepath does not exist, an FileNotFoundError
will be raised.
IsADirectoryError: If filepath is a directory, an IsADirectoryError
will be raised.
Examples:
>>> filepath = '/path/of/file'
>>> remove(filepath)
| def remove(
filepath: Union[str, Path],
backend_args: Optional[dict] = None,
) -> None:
"""Remove a file.
Args:
filepath (str, Path): Path to be removed.
backend_args (dict, optional): Arguments to instantiate the
corresponding backend. Defaults to None.
Raises:
FileNotFoundError: If filepath does not exist, an FileNotFoundError
will be raised.
IsADirectoryError: If filepath is a directory, an IsADirectoryError
will be raised.
Examples:
>>> filepath = '/path/of/file'
>>> remove(filepath)
"""
backend = get_file_backend(
filepath, backend_args=backend_args, enable_singleton=True)
backend.remove(filepath)
| (filepath: Union[str, pathlib.Path], backend_args: Optional[dict] = None) -> NoneType |
730,339 | mmengine.utils.misc | requires_executable | A decorator to check if some executable files are installed.
Example:
>>> @requires_executable('ffmpeg')
>>> func(arg1, args):
>>> print(1)
1
| def requires_executable(prerequisites):
"""A decorator to check if some executable files are installed.
Example:
>>> @requires_executable('ffmpeg')
>>> func(arg1, args):
>>> print(1)
1
"""
return check_prerequisites(prerequisites, checker=_check_executable)
| (prerequisites) |
730,340 | mmengine.utils.misc | requires_package | A decorator to check if some python packages are installed.
Example:
>>> @requires_package('numpy')
>>> func(arg1, args):
>>> return numpy.zeros(1)
array([0.])
>>> @requires_package(['numpy', 'non_package'])
>>> func(arg1, args):
>>> return numpy.zeros(1)
ImportError
| def requires_package(prerequisites):
"""A decorator to check if some python packages are installed.
Example:
>>> @requires_package('numpy')
>>> func(arg1, args):
>>> return numpy.zeros(1)
array([0.])
>>> @requires_package(['numpy', 'non_package'])
>>> func(arg1, args):
>>> return numpy.zeros(1)
ImportError
"""
return check_prerequisites(prerequisites, checker=_check_py_package)
| (prerequisites) |
730,341 | mmengine.fileio.io | rmtree | Recursively delete a directory tree.
Args:
dir_path (str or Path): A directory to be removed.
backend_args (dict, optional): Arguments to instantiate the
corresponding backend. Defaults to None.
Examples:
>>> dir_path = '/path/of/dir'
>>> rmtree(dir_path)
| def rmtree(
dir_path: Union[str, Path],
backend_args: Optional[dict] = None,
) -> None:
"""Recursively delete a directory tree.
Args:
dir_path (str or Path): A directory to be removed.
backend_args (dict, optional): Arguments to instantiate the
corresponding backend. Defaults to None.
Examples:
>>> dir_path = '/path/of/dir'
>>> rmtree(dir_path)
"""
backend = get_file_backend(
dir_path, backend_args=backend_args, enable_singleton=True)
backend.rmtree(dir_path)
| (dir_path: Union[str, pathlib.Path], backend_args: Optional[dict] = None) -> NoneType |
730,342 | mmengine.utils.path | scandir | Scan a directory to find the interested files.
Args:
dir_path (str | :obj:`Path`): Path of the directory.
suffix (str | tuple(str), optional): File suffix that we are
interested in. Defaults to None.
recursive (bool, optional): If set to True, recursively scan the
directory. Defaults to False.
case_sensitive (bool, optional) : If set to False, ignore the case of
suffix. Defaults to True.
Returns:
A generator for all the interested files with relative paths.
| def scandir(dir_path, suffix=None, recursive=False, case_sensitive=True):
"""Scan a directory to find the interested files.
Args:
dir_path (str | :obj:`Path`): Path of the directory.
suffix (str | tuple(str), optional): File suffix that we are
interested in. Defaults to None.
recursive (bool, optional): If set to True, recursively scan the
directory. Defaults to False.
case_sensitive (bool, optional) : If set to False, ignore the case of
suffix. Defaults to True.
Returns:
A generator for all the interested files with relative paths.
"""
if isinstance(dir_path, (str, Path)):
dir_path = str(dir_path)
else:
raise TypeError('"dir_path" must be a string or Path object')
if (suffix is not None) and not isinstance(suffix, (str, tuple)):
raise TypeError('"suffix" must be a string or tuple of strings')
if suffix is not None and not case_sensitive:
suffix = suffix.lower() if isinstance(suffix, str) else tuple(
item.lower() for item in suffix)
root = dir_path
def _scandir(dir_path, suffix, recursive, case_sensitive):
for entry in os.scandir(dir_path):
if not entry.name.startswith('.') and entry.is_file():
rel_path = osp.relpath(entry.path, root)
_rel_path = rel_path if case_sensitive else rel_path.lower()
if suffix is None or _rel_path.endswith(suffix):
yield rel_path
elif recursive and os.path.isdir(entry.path):
# scan recursively if entry.path is a directory
yield from _scandir(entry.path, suffix, recursive,
case_sensitive)
return _scandir(dir_path, suffix, recursive, case_sensitive)
| (dir_path, suffix=None, recursive=False, case_sensitive=True) |
730,343 | mmengine.utils.misc | slice_list | Slice a list into several sub lists by a list of given length.
Args:
in_list (list): The list to be sliced.
lens(int or list): The expected length of each out list.
Returns:
list: A list of sliced list.
| def slice_list(in_list, lens):
"""Slice a list into several sub lists by a list of given length.
Args:
in_list (list): The list to be sliced.
lens(int or list): The expected length of each out list.
Returns:
list: A list of sliced list.
"""
if isinstance(lens, int):
assert len(in_list) % lens == 0
lens = [lens] * int(len(in_list) / lens)
if not isinstance(lens, list):
raise TypeError('"indices" must be an integer or a list of integers')
elif sum(lens) != len(in_list):
raise ValueError('sum of lens and list length does not '
f'match: {sum(lens)} != {len(in_list)}')
out_list = []
idx = 0
for i in range(len(lens)):
out_list.append(in_list[idx:idx + lens[i]])
idx += lens[i]
return out_list
| (in_list, lens) |
730,344 | mmengine.utils.path | symlink | null | def symlink(src, dst, overwrite=True, **kwargs):
if os.path.lexists(dst) and overwrite:
os.remove(dst)
os.symlink(src, dst, **kwargs)
| (src, dst, overwrite=True, **kwargs) |
730,345 | mmengine.utils.misc | parse | null | def _ntuple(n):
def parse(x):
if isinstance(x, collections.abc.Iterable):
return x
return tuple(repeat(x, n))
return parse
| (x) |
730,350 | mmengine.utils.progressbar | track_iter_progress | Track the progress of tasks iteration or enumeration with a progress
bar.
Tasks are yielded with a simple for-loop.
Args:
tasks (Sequence): If tasks is a tuple, it must contain two elements,
the first being the tasks to be completed and the other being the
number of tasks. If it is not a tuple, it represents the tasks to
be completed.
bar_width (int): Width of progress bar.
Yields:
list: The task results.
| def track_iter_progress(tasks: Sequence, bar_width: int = 50, file=sys.stdout):
"""Track the progress of tasks iteration or enumeration with a progress
bar.
Tasks are yielded with a simple for-loop.
Args:
tasks (Sequence): If tasks is a tuple, it must contain two elements,
the first being the tasks to be completed and the other being the
number of tasks. If it is not a tuple, it represents the tasks to
be completed.
bar_width (int): Width of progress bar.
Yields:
list: The task results.
"""
if isinstance(tasks, tuple):
assert len(tasks) == 2
assert isinstance(tasks[0], Iterable)
assert isinstance(tasks[1], int)
task_num = tasks[1]
tasks = tasks[0] # type: ignore
elif isinstance(tasks, Sequence):
task_num = len(tasks)
else:
raise TypeError(
'"tasks" must be a tuple object or a sequence object, but got '
f'{type(tasks)}')
prog_bar = ProgressBar(task_num, bar_width, file=file)
for task in tasks:
yield task
prog_bar.update()
prog_bar.file.write('\n')
| (tasks: Sequence, bar_width: int = 50, file=<_io.TextIOWrapper name='<stdout>' mode='w' encoding='utf-8'>) |
730,351 | mmengine.utils.progressbar | track_parallel_progress | Track the progress of parallel task execution with a progress bar.
The built-in :mod:`multiprocessing` module is used for process pools and
tasks are done with :func:`Pool.map` or :func:`Pool.imap_unordered`.
Args:
func (callable): The function to be applied to each task.
tasks (Sequence): If tasks is a tuple, it must contain two elements,
the first being the tasks to be completed and the other being the
number of tasks. If it is not a tuple, it represents the tasks to
be completed.
nproc (int): Process (worker) number.
initializer (None or callable): Refer to :class:`multiprocessing.Pool`
for details.
initargs (None or tuple): Refer to :class:`multiprocessing.Pool` for
details.
chunksize (int): Refer to :class:`multiprocessing.Pool` for details.
bar_width (int): Width of progress bar.
skip_first (bool): Whether to skip the first sample for each worker
when estimating fps, since the initialization step may takes
longer.
keep_order (bool): If True, :func:`Pool.imap` is used, otherwise
:func:`Pool.imap_unordered` is used.
Returns:
list: The task results.
| def track_parallel_progress(func: Callable,
tasks: Sequence,
nproc: int,
initializer: Callable = None,
initargs: tuple = None,
bar_width: int = 50,
chunksize: int = 1,
skip_first: bool = False,
keep_order: bool = True,
file=sys.stdout):
"""Track the progress of parallel task execution with a progress bar.
The built-in :mod:`multiprocessing` module is used for process pools and
tasks are done with :func:`Pool.map` or :func:`Pool.imap_unordered`.
Args:
func (callable): The function to be applied to each task.
tasks (Sequence): If tasks is a tuple, it must contain two elements,
the first being the tasks to be completed and the other being the
number of tasks. If it is not a tuple, it represents the tasks to
be completed.
nproc (int): Process (worker) number.
initializer (None or callable): Refer to :class:`multiprocessing.Pool`
for details.
initargs (None or tuple): Refer to :class:`multiprocessing.Pool` for
details.
chunksize (int): Refer to :class:`multiprocessing.Pool` for details.
bar_width (int): Width of progress bar.
skip_first (bool): Whether to skip the first sample for each worker
when estimating fps, since the initialization step may takes
longer.
keep_order (bool): If True, :func:`Pool.imap` is used, otherwise
:func:`Pool.imap_unordered` is used.
Returns:
list: The task results.
"""
if isinstance(tasks, tuple):
assert len(tasks) == 2
assert isinstance(tasks[0], Iterable)
assert isinstance(tasks[1], int)
task_num = tasks[1]
tasks = tasks[0] # type: ignore
elif isinstance(tasks, Sequence):
task_num = len(tasks)
else:
raise TypeError(
'"tasks" must be a tuple object or a sequence object, but got '
f'{type(tasks)}')
pool = init_pool(nproc, initializer, initargs)
start = not skip_first
task_num -= nproc * chunksize * int(skip_first)
prog_bar = ProgressBar(task_num, bar_width, start, file=file)
results = []
if keep_order:
gen = pool.imap(func, tasks, chunksize)
else:
gen = pool.imap_unordered(func, tasks, chunksize)
for result in gen:
results.append(result)
if skip_first:
if len(results) < nproc * chunksize:
continue
elif len(results) == nproc * chunksize:
prog_bar.start()
continue
prog_bar.update()
prog_bar.file.write('\n')
pool.close()
pool.join()
return results
| (func: Callable, tasks: Sequence, nproc: int, initializer: Optional[Callable] = None, initargs: Optional[tuple] = None, bar_width: int = 50, chunksize: int = 1, skip_first: bool = False, keep_order: bool = True, file=<_io.TextIOWrapper name='<stdout>' mode='w' encoding='utf-8'>) |
730,352 | mmengine.utils.progressbar | track_progress | Track the progress of tasks execution with a progress bar.
Tasks are done with a simple for-loop.
Args:
func (callable): The function to be applied to each task.
tasks (Sequence): If tasks is a tuple, it must contain two elements,
the first being the tasks to be completed and the other being the
number of tasks. If it is not a tuple, it represents the tasks to
be completed.
bar_width (int): Width of progress bar.
Returns:
list: The task results.
| def track_progress(func: Callable,
tasks: Sequence,
bar_width: int = 50,
file=sys.stdout,
**kwargs):
"""Track the progress of tasks execution with a progress bar.
Tasks are done with a simple for-loop.
Args:
func (callable): The function to be applied to each task.
tasks (Sequence): If tasks is a tuple, it must contain two elements,
the first being the tasks to be completed and the other being the
number of tasks. If it is not a tuple, it represents the tasks to
be completed.
bar_width (int): Width of progress bar.
Returns:
list: The task results.
"""
if isinstance(tasks, tuple):
assert len(tasks) == 2
assert isinstance(tasks[0], Iterable)
assert isinstance(tasks[1], int)
task_num = tasks[1]
tasks = tasks[0] # type: ignore
elif isinstance(tasks, Sequence):
task_num = len(tasks)
else:
raise TypeError(
'"tasks" must be a tuple object or a sequence object, but got '
f'{type(tasks)}')
prog_bar = ProgressBar(task_num, bar_width, file=file)
results = []
for task in tasks:
results.append(func(task, **kwargs))
prog_bar.update()
prog_bar.file.write('\n')
return results
| (func: Callable, tasks: Sequence, bar_width: int = 50, file=<_io.TextIOWrapper name='<stdout>' mode='w' encoding='utf-8'>, **kwargs) |
730,353 | mmengine.utils.progressbar_rich | track_progress_rich | Track the progress of parallel task execution with a progress bar. The
built-in :mod:`multiprocessing` module is used for process pools and tasks
are done with :func:`Pool.map` or :func:`Pool.imap_unordered`.
Args:
func (callable): The function to be applied to each task.
tasks (Iterable or Sized): A tuple of tasks. There are several cases
for different format tasks:
- When ``func`` accepts no arguments: tasks should be an empty
tuple, and ``task_num`` must be specified.
- When ``func`` accepts only one argument: tasks should be a tuple
containing the argument.
- When ``func`` accepts multiple arguments: tasks should be a
tuple, with each element representing a set of arguments.
If an element is a ``dict``, it will be parsed as a set of
keyword-only arguments.
Defaults to an empty tuple.
task_num (int, optional): If ``tasks`` is an iterator which does not
have length, the number of tasks can be provided by ``task_num``.
Defaults to None.
nproc (int): Process (worker) number, if nuproc is 1,
use single process. Defaults to 1.
chunksize (int): Refer to :class:`multiprocessing.Pool` for details.
Defaults to 1.
description (str): The description of progress bar.
Defaults to "Process".
color (str): The color of progress bar. Defaults to "blue".
Examples:
>>> import time
>>> def func(x):
... time.sleep(1)
... return x**2
>>> track_progress_rich(func, range(10), nproc=2)
Returns:
list: The task results.
| def track_progress_rich(func: Callable,
tasks: Iterable = tuple(),
task_num: int = None,
nproc: int = 1,
chunksize: int = 1,
description: str = 'Processing',
color: str = 'blue') -> list:
"""Track the progress of parallel task execution with a progress bar. The
built-in :mod:`multiprocessing` module is used for process pools and tasks
are done with :func:`Pool.map` or :func:`Pool.imap_unordered`.
Args:
func (callable): The function to be applied to each task.
tasks (Iterable or Sized): A tuple of tasks. There are several cases
for different format tasks:
- When ``func`` accepts no arguments: tasks should be an empty
tuple, and ``task_num`` must be specified.
- When ``func`` accepts only one argument: tasks should be a tuple
containing the argument.
- When ``func`` accepts multiple arguments: tasks should be a
tuple, with each element representing a set of arguments.
If an element is a ``dict``, it will be parsed as a set of
keyword-only arguments.
Defaults to an empty tuple.
task_num (int, optional): If ``tasks`` is an iterator which does not
have length, the number of tasks can be provided by ``task_num``.
Defaults to None.
nproc (int): Process (worker) number, if nuproc is 1,
use single process. Defaults to 1.
chunksize (int): Refer to :class:`multiprocessing.Pool` for details.
Defaults to 1.
description (str): The description of progress bar.
Defaults to "Process".
color (str): The color of progress bar. Defaults to "blue".
Examples:
>>> import time
>>> def func(x):
... time.sleep(1)
... return x**2
>>> track_progress_rich(func, range(10), nproc=2)
Returns:
list: The task results.
"""
if not callable(func):
raise TypeError('func must be a callable object')
if not isinstance(tasks, Iterable):
raise TypeError(
f'tasks must be an iterable object, but got {type(tasks)}')
if isinstance(tasks, Sized):
if len(tasks) == 0:
if task_num is None:
raise ValueError('If tasks is an empty iterable, '
'task_num must be set')
else:
tasks = tuple(tuple() for _ in range(task_num))
else:
if task_num is not None and task_num != len(tasks):
raise ValueError('task_num does not match the length of tasks')
task_num = len(tasks)
if nproc <= 0:
raise ValueError('nproc must be a positive number')
skip_times = nproc * chunksize if nproc > 1 else 0
prog_bar = Progress(
TextColumn('{task.description}'),
BarColumn(),
_SkipFirstTimeRemainingColumn(skip_times=skip_times),
MofNCompleteColumn(),
TaskProgressColumn(show_speed=True),
)
worker = _Worker(func)
task_id = prog_bar.add_task(
total=task_num, color=color, description=description)
tasks = _tasks_with_index(tasks)
# Use single process when nproc is 1, else use multiprocess.
with prog_bar:
if nproc == 1:
results = []
for task in tasks:
results.append(worker(task)[0])
prog_bar.update(task_id, advance=1, refresh=True)
else:
with Pool(nproc) as pool:
results = []
unordered_results = []
gen = pool.imap_unordered(worker, tasks, chunksize)
try:
for result in gen:
result, idx = result
unordered_results.append((result, idx))
results.append(None)
prog_bar.update(task_id, advance=1, refresh=True)
except Exception as e:
prog_bar.stop()
raise e
for result, idx in unordered_results:
results[idx] = result
return results
| (func: Callable, tasks: Iterable = (), task_num: Optional[int] = None, nproc: int = 1, chunksize: int = 1, description: str = 'Processing', color: str = 'blue') -> list |
730,354 | mmengine.registry.utils | traverse_registry_tree | Traverse the whole registry tree from any given node, and collect
information of all registered modules in this registry tree.
Args:
registry (Registry): a registry node in the registry tree.
verbose (bool): Whether to print log. Defaults to True
Returns:
list: Statistic results of all modules in each node of the registry
tree.
| def traverse_registry_tree(registry: Registry, verbose: bool = True) -> list:
"""Traverse the whole registry tree from any given node, and collect
information of all registered modules in this registry tree.
Args:
registry (Registry): a registry node in the registry tree.
verbose (bool): Whether to print log. Defaults to True
Returns:
list: Statistic results of all modules in each node of the registry
tree.
"""
root_registry = registry.root
modules_info = []
def _dfs_registry(_registry):
if isinstance(_registry, Registry):
num_modules = len(_registry.module_dict)
scope = _registry.scope
registry_info = dict(num_modules=num_modules, scope=scope)
for name, registered_class in _registry.module_dict.items():
folder = '/'.join(registered_class.__module__.split('.')[:-1])
if folder in registry_info:
registry_info[folder].append(name)
else:
registry_info[folder] = [name]
if verbose:
print_log(
f"Find {num_modules} modules in {scope}'s "
f"'{_registry.name}' registry ",
logger='current')
modules_info.append(registry_info)
else:
return
for _, child in _registry.children.items():
_dfs_registry(child)
_dfs_registry(root_registry)
return modules_info
| (registry: mmengine.registry.registry.Registry, verbose: bool = True) -> list |
730,355 | mmengine.utils.misc | tuple_cast | Cast elements of an iterable object into a tuple of some type.
A partial method of :func:`iter_cast`.
| def tuple_cast(inputs, dst_type):
"""Cast elements of an iterable object into a tuple of some type.
A partial method of :func:`iter_cast`.
"""
return iter_cast(inputs, dst_type, return_type=tuple)
| (inputs, dst_type) |
730,358 | datasette_query_history | extra_css_urls | null | @hookimpl
def extra_css_urls(database, table, columns, view_name, datasette):
return [
"/-/static-plugins/datasette_query_history/datasette-query-history.css",
]
| (database, table, columns, view_name, datasette) |
730,359 | datasette_query_history | extra_js_urls | null | @hookimpl
def extra_js_urls(database, table, columns, view_name, datasette):
return [
"/-/static-plugins/datasette_query_history/datasette-query-history.js",
]
| (database, table, columns, view_name, datasette) |
730,360 | jupytercad_freecad | _jupyter_labextension_paths | null | def _jupyter_labextension_paths():
return [{"src": "labextension", "dest": "@jupytercad/jupytercad-freecad"}]
| () |
730,361 | jupytercad_freecad | _jupyter_server_extension_points | null | def _jupyter_server_extension_points():
return [{"module": "jupytercad_freecad"}]
| () |
730,362 | jupytercad_freecad | _load_jupyter_server_extension | Registers the API handler to receive HTTP requests from the frontend extension.
Parameters
----------
server_app: jupyterlab.labapp.LabApp
JupyterLab application instance
| def _load_jupyter_server_extension(server_app):
"""Registers the API handler to receive HTTP requests from the frontend extension.
Parameters
----------
server_app: jupyterlab.labapp.LabApp
JupyterLab application instance
"""
setup_handlers(server_app.web_app)
name = "jupytercad_freecad"
server_app.log.info(f"Registered {name} server extension")
| (server_app) |
730,365 | jupytercad_freecad.handlers | setup_handlers | null | def setup_handlers(web_app):
host_pattern = ".*$"
base_url = web_app.settings["base_url"]
route_pattern = url_path_join(base_url, "jupytercad_freecad", "backend-check")
handlers = [(route_pattern, BackendCheckHandler)]
web_app.add_handlers(host_pattern, handlers)
| (web_app) |
730,366 | chromadb.api | AdminAPI | null | class AdminAPI(ABC):
@abstractmethod
def create_database(self, name: str, tenant: str = DEFAULT_TENANT) -> None:
"""Create a new database. Raises an error if the database already exists.
Args:
database: The name of the database to create.
"""
pass
@abstractmethod
def get_database(self, name: str, tenant: str = DEFAULT_TENANT) -> Database:
"""Get a database. Raises an error if the database does not exist.
Args:
database: The name of the database to get.
tenant: The tenant of the database to get.
"""
pass
@abstractmethod
def create_tenant(self, name: str) -> None:
"""Create a new tenant. Raises an error if the tenant already exists.
Args:
tenant: The name of the tenant to create.
"""
pass
@abstractmethod
def get_tenant(self, name: str) -> Tenant:
"""Get a tenant. Raises an error if the tenant does not exist.
Args:
tenant: The name of the tenant to get.
"""
pass
| () |
730,367 | chromadb.api | create_database | Create a new database. Raises an error if the database already exists.
Args:
database: The name of the database to create.
| @abstractmethod
def create_database(self, name: str, tenant: str = DEFAULT_TENANT) -> None:
"""Create a new database. Raises an error if the database already exists.
Args:
database: The name of the database to create.
"""
pass
| (self, name: str, tenant: str = 'default_tenant') -> NoneType |
730,368 | chromadb.api | create_tenant | Create a new tenant. Raises an error if the tenant already exists.
Args:
tenant: The name of the tenant to create.
| @abstractmethod
def create_tenant(self, name: str) -> None:
"""Create a new tenant. Raises an error if the tenant already exists.
Args:
tenant: The name of the tenant to create.
"""
pass
| (self, name: str) -> NoneType |
730,369 | chromadb.api | get_database | Get a database. Raises an error if the database does not exist.
Args:
database: The name of the database to get.
tenant: The tenant of the database to get.
| @abstractmethod
def get_database(self, name: str, tenant: str = DEFAULT_TENANT) -> Database:
"""Get a database. Raises an error if the database does not exist.
Args:
database: The name of the database to get.
tenant: The tenant of the database to get.
"""
pass
| (self, name: str, tenant: str = 'default_tenant') -> chromadb.types.Database |
730,370 | chromadb.api | get_tenant | Get a tenant. Raises an error if the tenant does not exist.
Args:
tenant: The name of the tenant to get.
| @abstractmethod
def get_tenant(self, name: str) -> Tenant:
"""Get a tenant. Raises an error if the tenant does not exist.
Args:
tenant: The name of the tenant to get.
"""
pass
| (self, name: str) -> chromadb.types.Tenant |
730,371 | chromadb | AdminClient |
Creates an admin client that can be used to create tenants and databases.
| def AdminClient(settings: Settings = Settings()) -> AdminAPI:
"""
Creates an admin client that can be used to create tenants and databases.
"""
return AdminClientCreator(settings=settings)
| (settings: chromadb.config.Settings = Settings(environment='', chroma_api_impl='chromadb.api.segment.SegmentAPI', chroma_server_nofile=None, chroma_server_thread_pool_size=40, tenant_id='default', topic_namespace='default', chroma_server_host=None, chroma_server_headers=None, chroma_server_http_port=None, chroma_server_ssl_enabled=False, chroma_server_ssl_verify=None, chroma_server_api_default_path='/api/v1', chroma_server_cors_allow_origins=[], is_persistent=False, persist_directory='./chroma', chroma_memory_limit_bytes=0, chroma_segment_cache_policy=None, allow_reset=False, chroma_auth_token_transport_header=None, chroma_client_auth_provider=None, chroma_client_auth_credentials=None, chroma_server_auth_ignore_paths={'/api/v1': ['GET'], '/api/v1/heartbeat': ['GET'], '/api/v1/version': ['GET']}, chroma_overwrite_singleton_tenant_database_access_from_auth=False, chroma_server_authn_provider=None, chroma_server_authn_credentials=None, chroma_server_authn_credentials_file=None, chroma_server_authz_provider=None, chroma_server_authz_config=None, chroma_server_authz_config_file=None, chroma_product_telemetry_impl='chromadb.telemetry.product.posthog.Posthog', chroma_telemetry_impl='chromadb.telemetry.product.posthog.Posthog', anonymized_telemetry=True, chroma_otel_collection_endpoint='', chroma_otel_service_name='chromadb', chroma_otel_collection_headers={}, chroma_otel_granularity=None, migrations='apply', migrations_hash_algorithm='md5', chroma_segment_directory_impl='chromadb.segment.impl.distributed.segment_directory.RendezvousHashSegmentDirectory', chroma_memberlist_provider_impl='chromadb.segment.impl.distributed.segment_directory.CustomResourceMemberlistProvider', worker_memberlist_name='query-service-memberlist', chroma_server_grpc_port=None, chroma_sysdb_impl='chromadb.db.impl.sqlite.SqliteDB', chroma_producer_impl='chromadb.db.impl.sqlite.SqliteDB', chroma_consumer_impl='chromadb.db.impl.sqlite.SqliteDB', chroma_segment_manager_impl='chromadb.segment.impl.manager.local.LocalSegmentManager', chroma_quota_provider_impl=None, chroma_rate_limiting_provider_impl=None, chroma_db_impl=None, chroma_collection_assignment_policy_impl='chromadb.ingest.impl.simple_policy.SimpleAssignmentPolicy', chroma_coordinator_host='localhost', chroma_logservice_host='localhost', chroma_logservice_port=50052)) -> chromadb.api.AdminAPI |
730,372 | chromadb.api.client | AdminClient | null | class AdminClient(SharedSystemClient, AdminAPI):
_server: ServerAPI
def __init__(self, settings: Settings = Settings()) -> None:
super().__init__(settings)
self._server = self._system.instance(ServerAPI)
@override
def create_database(self, name: str, tenant: str = DEFAULT_TENANT) -> None:
return self._server.create_database(name=name, tenant=tenant)
@override
def get_database(self, name: str, tenant: str = DEFAULT_TENANT) -> Database:
return self._server.get_database(name=name, tenant=tenant)
@override
def create_tenant(self, name: str) -> None:
return self._server.create_tenant(name=name)
@override
def get_tenant(self, name: str) -> Tenant:
return self._server.get_tenant(name=name)
@classmethod
@override
def from_system(
cls,
system: System,
) -> "AdminClient":
SharedSystemClient._populate_data_from_system(system)
instance = cls(settings=system.settings)
return instance
| (settings: chromadb.config.Settings = Settings(environment='', chroma_api_impl='chromadb.api.segment.SegmentAPI', chroma_server_nofile=None, chroma_server_thread_pool_size=40, tenant_id='default', topic_namespace='default', chroma_server_host=None, chroma_server_headers=None, chroma_server_http_port=None, chroma_server_ssl_enabled=False, chroma_server_ssl_verify=None, chroma_server_api_default_path='/api/v1', chroma_server_cors_allow_origins=[], is_persistent=False, persist_directory='./chroma', chroma_memory_limit_bytes=0, chroma_segment_cache_policy=None, allow_reset=False, chroma_auth_token_transport_header=None, chroma_client_auth_provider=None, chroma_client_auth_credentials=None, chroma_server_auth_ignore_paths={'/api/v1': ['GET'], '/api/v1/heartbeat': ['GET'], '/api/v1/version': ['GET']}, chroma_overwrite_singleton_tenant_database_access_from_auth=False, chroma_server_authn_provider=None, chroma_server_authn_credentials=None, chroma_server_authn_credentials_file=None, chroma_server_authz_provider=None, chroma_server_authz_config=None, chroma_server_authz_config_file=None, chroma_product_telemetry_impl='chromadb.telemetry.product.posthog.Posthog', chroma_telemetry_impl='chromadb.telemetry.product.posthog.Posthog', anonymized_telemetry=True, chroma_otel_collection_endpoint='', chroma_otel_service_name='chromadb', chroma_otel_collection_headers={}, chroma_otel_granularity=None, migrations='apply', migrations_hash_algorithm='md5', chroma_segment_directory_impl='chromadb.segment.impl.distributed.segment_directory.RendezvousHashSegmentDirectory', chroma_memberlist_provider_impl='chromadb.segment.impl.distributed.segment_directory.CustomResourceMemberlistProvider', worker_memberlist_name='query-service-memberlist', chroma_server_grpc_port=None, chroma_sysdb_impl='chromadb.db.impl.sqlite.SqliteDB', chroma_producer_impl='chromadb.db.impl.sqlite.SqliteDB', chroma_consumer_impl='chromadb.db.impl.sqlite.SqliteDB', chroma_segment_manager_impl='chromadb.segment.impl.manager.local.LocalSegmentManager', chroma_quota_provider_impl=None, chroma_rate_limiting_provider_impl=None, chroma_db_impl=None, chroma_collection_assignment_policy_impl='chromadb.ingest.impl.simple_policy.SimpleAssignmentPolicy', chroma_coordinator_host='localhost', chroma_logservice_host='localhost', chroma_logservice_port=50052)) -> None |
730,373 | chromadb.api.client | __init__ | null | def __init__(self, settings: Settings = Settings()) -> None:
super().__init__(settings)
self._server = self._system.instance(ServerAPI)
| (self, settings: chromadb.config.Settings = Settings(environment='', chroma_api_impl='chromadb.api.segment.SegmentAPI', chroma_server_nofile=None, chroma_server_thread_pool_size=40, tenant_id='default', topic_namespace='default', chroma_server_host=None, chroma_server_headers=None, chroma_server_http_port=None, chroma_server_ssl_enabled=False, chroma_server_ssl_verify=None, chroma_server_api_default_path='/api/v1', chroma_server_cors_allow_origins=[], is_persistent=False, persist_directory='./chroma', chroma_memory_limit_bytes=0, chroma_segment_cache_policy=None, allow_reset=False, chroma_auth_token_transport_header=None, chroma_client_auth_provider=None, chroma_client_auth_credentials=None, chroma_server_auth_ignore_paths={'/api/v1': ['GET'], '/api/v1/heartbeat': ['GET'], '/api/v1/version': ['GET']}, chroma_overwrite_singleton_tenant_database_access_from_auth=False, chroma_server_authn_provider=None, chroma_server_authn_credentials=None, chroma_server_authn_credentials_file=None, chroma_server_authz_provider=None, chroma_server_authz_config=None, chroma_server_authz_config_file=None, chroma_product_telemetry_impl='chromadb.telemetry.product.posthog.Posthog', chroma_telemetry_impl='chromadb.telemetry.product.posthog.Posthog', anonymized_telemetry=True, chroma_otel_collection_endpoint='', chroma_otel_service_name='chromadb', chroma_otel_collection_headers={}, chroma_otel_granularity=None, migrations='apply', migrations_hash_algorithm='md5', chroma_segment_directory_impl='chromadb.segment.impl.distributed.segment_directory.RendezvousHashSegmentDirectory', chroma_memberlist_provider_impl='chromadb.segment.impl.distributed.segment_directory.CustomResourceMemberlistProvider', worker_memberlist_name='query-service-memberlist', chroma_server_grpc_port=None, chroma_sysdb_impl='chromadb.db.impl.sqlite.SqliteDB', chroma_producer_impl='chromadb.db.impl.sqlite.SqliteDB', chroma_consumer_impl='chromadb.db.impl.sqlite.SqliteDB', chroma_segment_manager_impl='chromadb.segment.impl.manager.local.LocalSegmentManager', chroma_quota_provider_impl=None, chroma_rate_limiting_provider_impl=None, chroma_db_impl=None, chroma_collection_assignment_policy_impl='chromadb.ingest.impl.simple_policy.SimpleAssignmentPolicy', chroma_coordinator_host='localhost', chroma_logservice_host='localhost', chroma_logservice_port=50052)) -> NoneType |
730,374 | chromadb.api.client | _get_identifier_from_settings | null | @staticmethod
def _get_identifier_from_settings(settings: Settings) -> str:
identifier = ""
api_impl = settings.chroma_api_impl
if api_impl is None:
raise ValueError("Chroma API implementation must be set in settings")
elif api_impl == "chromadb.api.segment.SegmentAPI":
if settings.is_persistent:
identifier = settings.persist_directory
else:
identifier = (
"ephemeral" # TODO: support pathing and multiple ephemeral clients
)
elif api_impl == "chromadb.api.fastapi.FastAPI":
# FastAPI clients can all use unique system identifiers since their configurations can be independent, e.g. different auth tokens
identifier = str(uuid.uuid4())
else:
raise ValueError(f"Unsupported Chroma API implementation {api_impl}")
return identifier
| (settings: chromadb.config.Settings) -> str |
730,375 | chromadb.api.client | _populate_data_from_system | null | @staticmethod
def _populate_data_from_system(system: System) -> str:
identifier = SharedSystemClient._get_identifier_from_settings(system.settings)
SharedSystemClient._identifer_to_system[identifier] = system
return identifier
| (system: chromadb.config.System) -> str |
730,376 | chromadb.api.client | clear_system_cache | null | @staticmethod
def clear_system_cache() -> None:
SharedSystemClient._identifer_to_system = {}
| () -> NoneType |
730,377 | chromadb.api.client | create_database | Create a new database. Raises an error if the database already exists.
Args:
database: The name of the database to create.
| @override
def create_database(self, name: str, tenant: str = DEFAULT_TENANT) -> None:
return self._server.create_database(name=name, tenant=tenant)
| (self, name: str, tenant: str = 'default_tenant') -> NoneType |
730,378 | chromadb.api.client | create_tenant | Create a new tenant. Raises an error if the tenant already exists.
Args:
tenant: The name of the tenant to create.
| @override
def create_tenant(self, name: str) -> None:
return self._server.create_tenant(name=name)
| (self, name: str) -> NoneType |
730,379 | chromadb.api.client | get_database | Get a database. Raises an error if the database does not exist.
Args:
database: The name of the database to get.
tenant: The tenant of the database to get.
| @override
def get_database(self, name: str, tenant: str = DEFAULT_TENANT) -> Database:
return self._server.get_database(name=name, tenant=tenant)
| (self, name: str, tenant: str = 'default_tenant') -> chromadb.types.Database |
730,380 | chromadb.api.client | get_tenant | Get a tenant. Raises an error if the tenant does not exist.
Args:
tenant: The name of the tenant to get.
| @override
def get_tenant(self, name: str) -> Tenant:
return self._server.get_tenant(name=name)
| (self, name: str) -> chromadb.types.Tenant |
730,381 | chromadb | Client |
Return a running chroma.API instance
tenant: The tenant to use for this client. Defaults to the default tenant.
database: The database to use for this client. Defaults to the default database.
| def Client(
settings: Settings = __settings,
tenant: str = DEFAULT_TENANT,
database: str = DEFAULT_DATABASE,
) -> ClientAPI:
"""
Return a running chroma.API instance
tenant: The tenant to use for this client. Defaults to the default tenant.
database: The database to use for this client. Defaults to the default database.
"""
# Make sure paramaters are the correct types -- users can pass anything.
tenant = str(tenant)
database = str(database)
return ClientCreator(tenant=tenant, database=database, settings=settings)
| (settings: chromadb.config.Settings = Settings(environment='', chroma_api_impl='chromadb.api.segment.SegmentAPI', chroma_server_nofile=None, chroma_server_thread_pool_size=40, tenant_id='default', topic_namespace='default', chroma_server_host=None, chroma_server_headers=None, chroma_server_http_port=None, chroma_server_ssl_enabled=False, chroma_server_ssl_verify=None, chroma_server_api_default_path='/api/v1', chroma_server_cors_allow_origins=[], is_persistent=False, persist_directory='./chroma', chroma_memory_limit_bytes=0, chroma_segment_cache_policy=None, allow_reset=False, chroma_auth_token_transport_header=None, chroma_client_auth_provider=None, chroma_client_auth_credentials=None, chroma_server_auth_ignore_paths={'/api/v1': ['GET'], '/api/v1/heartbeat': ['GET'], '/api/v1/version': ['GET']}, chroma_overwrite_singleton_tenant_database_access_from_auth=False, chroma_server_authn_provider=None, chroma_server_authn_credentials=None, chroma_server_authn_credentials_file=None, chroma_server_authz_provider=None, chroma_server_authz_config=None, chroma_server_authz_config_file=None, chroma_product_telemetry_impl='chromadb.telemetry.product.posthog.Posthog', chroma_telemetry_impl='chromadb.telemetry.product.posthog.Posthog', anonymized_telemetry=True, chroma_otel_collection_endpoint='', chroma_otel_service_name='chromadb', chroma_otel_collection_headers={}, chroma_otel_granularity=None, migrations='apply', migrations_hash_algorithm='md5', chroma_segment_directory_impl='chromadb.segment.impl.distributed.segment_directory.RendezvousHashSegmentDirectory', chroma_memberlist_provider_impl='chromadb.segment.impl.distributed.segment_directory.CustomResourceMemberlistProvider', worker_memberlist_name='query-service-memberlist', chroma_server_grpc_port=None, chroma_sysdb_impl='chromadb.db.impl.sqlite.SqliteDB', chroma_producer_impl='chromadb.db.impl.sqlite.SqliteDB', chroma_consumer_impl='chromadb.db.impl.sqlite.SqliteDB', chroma_segment_manager_impl='chromadb.segment.impl.manager.local.LocalSegmentManager', chroma_quota_provider_impl=None, chroma_rate_limiting_provider_impl=None, chroma_db_impl=None, chroma_collection_assignment_policy_impl='chromadb.ingest.impl.simple_policy.SimpleAssignmentPolicy', chroma_coordinator_host='localhost', chroma_logservice_host='localhost', chroma_logservice_port=50052), tenant: str = 'default_tenant', database: str = 'default_database') -> chromadb.api.ClientAPI |
730,382 | chromadb.api | ClientAPI | null | class ClientAPI(BaseAPI, ABC):
tenant: str
database: str
@abstractmethod
def set_tenant(self, tenant: str, database: str = DEFAULT_DATABASE) -> None:
"""Set the tenant and database for the client. Raises an error if the tenant or
database does not exist.
Args:
tenant: The tenant to set.
database: The database to set.
"""
pass
@abstractmethod
def set_database(self, database: str) -> None:
"""Set the database for the client. Raises an error if the database does not exist.
Args:
database: The database to set.
"""
pass
@staticmethod
@abstractmethod
def clear_system_cache() -> None:
"""Clear the system cache so that new systems can be created for an existing path.
This should only be used for testing purposes."""
pass
| () |
730,383 | chromadb.api | _add | [Internal] Add embeddings to a collection specified by UUID.
If (some) ids already exist, only the new embeddings will be added.
Args:
ids: The ids to associate with the embeddings.
collection_id: The UUID of the collection to add the embeddings to.
embedding: The sequence of embeddings to add.
metadata: The metadata to associate with the embeddings. Defaults to None.
documents: The documents to associate with the embeddings. Defaults to None.
uris: URIs of data sources for each embedding. Defaults to None.
Returns:
True if the embeddings were added successfully.
| @abstractmethod
def _add(
self,
ids: IDs,
collection_id: UUID,
embeddings: Embeddings,
metadatas: Optional[Metadatas] = None,
documents: Optional[Documents] = None,
uris: Optional[URIs] = None,
) -> bool:
"""[Internal] Add embeddings to a collection specified by UUID.
If (some) ids already exist, only the new embeddings will be added.
Args:
ids: The ids to associate with the embeddings.
collection_id: The UUID of the collection to add the embeddings to.
embedding: The sequence of embeddings to add.
metadata: The metadata to associate with the embeddings. Defaults to None.
documents: The documents to associate with the embeddings. Defaults to None.
uris: URIs of data sources for each embedding. Defaults to None.
Returns:
True if the embeddings were added successfully.
"""
pass
| (self, ids: List[str], collection_id: uuid.UUID, embeddings: List[Union[Sequence[float], Sequence[int]]], metadatas: Optional[List[Mapping[str, Union[str, int, float, bool]]]] = None, documents: Optional[List[str]] = None, uris: Optional[List[str]] = None) -> bool |
730,384 | chromadb.api | _count | [Internal] Returns the number of entries in a collection specified by UUID.
Args:
collection_id: The UUID of the collection to count the embeddings in.
Returns:
int: The number of embeddings in the collection
| @abstractmethod
def _count(self, collection_id: UUID) -> int:
"""[Internal] Returns the number of entries in a collection specified by UUID.
Args:
collection_id: The UUID of the collection to count the embeddings in.
Returns:
int: The number of embeddings in the collection
"""
pass
| (self, collection_id: uuid.UUID) -> int |
730,385 | chromadb.api | _delete | [Internal] Deletes entries from a collection specified by UUID.
Args:
collection_id: The UUID of the collection to delete the entries from.
ids: The IDs of the entries to delete. Defaults to None.
where: Conditional filtering on metadata. Defaults to {}.
where_document: Conditional filtering on documents. Defaults to {}.
Returns:
IDs: The list of IDs of the entries that were deleted.
| @abstractmethod
def _delete(
self,
collection_id: UUID,
ids: Optional[IDs],
where: Optional[Where] = {},
where_document: Optional[WhereDocument] = {},
) -> IDs:
"""[Internal] Deletes entries from a collection specified by UUID.
Args:
collection_id: The UUID of the collection to delete the entries from.
ids: The IDs of the entries to delete. Defaults to None.
where: Conditional filtering on metadata. Defaults to {}.
where_document: Conditional filtering on documents. Defaults to {}.
Returns:
IDs: The list of IDs of the entries that were deleted.
"""
pass
| (self, collection_id: uuid.UUID, ids: Optional[List[str]], where: Optional[Dict[Union[str, Literal['$and'], Literal['$or']], Union[str, int, float, bool, Dict[Union[Literal['$gt'], Literal['$gte'], Literal['$lt'], Literal['$lte'], Literal['$ne'], Literal['$eq'], Literal['$and'], Literal['$or']], Union[str, int, float, bool]], Dict[Union[Literal['$in'], Literal['$nin']], List[Union[str, int, float, bool]]], List[Dict[Union[str, Literal['$and'], Literal['$or']], Union[str, int, float, bool, Dict[Union[Literal['$gt'], Literal['$gte'], Literal['$lt'], Literal['$lte'], Literal['$ne'], Literal['$eq'], Literal['$and'], Literal['$or']], Union[str, int, float, bool]], Dict[Union[Literal['$in'], Literal['$nin']], List[Union[str, int, float, bool]]], List[ForwardRef('Where')]]]]]]] = {}, where_document: Optional[Dict[Union[Literal['$contains'], Literal['$not_contains'], Literal['$and'], Literal['$or']], Union[str, List[Dict[Union[Literal['$contains'], Literal['$not_contains'], Literal['$and'], Literal['$or']], Union[str, List[ForwardRef('WhereDocument')]]]]]]] = {}) -> List[str] |
730,386 | chromadb.api | _get | [Internal] Returns entries from a collection specified by UUID.
Args:
ids: The IDs of the entries to get. Defaults to None.
where: Conditional filtering on metadata. Defaults to {}.
sort: The column to sort the entries by. Defaults to None.
limit: The maximum number of entries to return. Defaults to None.
offset: The number of entries to skip before returning. Defaults to None.
page: The page number to return. Defaults to None.
page_size: The number of entries to return per page. Defaults to None.
where_document: Conditional filtering on documents. Defaults to {}.
include: The fields to include in the response.
Defaults to ["embeddings", "metadatas", "documents"].
Returns:
GetResult: The entries in the collection that match the query.
| @abstractmethod
def _get(
self,
collection_id: UUID,
ids: Optional[IDs] = None,
where: Optional[Where] = {},
sort: Optional[str] = None,
limit: Optional[int] = None,
offset: Optional[int] = None,
page: Optional[int] = None,
page_size: Optional[int] = None,
where_document: Optional[WhereDocument] = {},
include: Include = ["embeddings", "metadatas", "documents"],
) -> GetResult:
"""[Internal] Returns entries from a collection specified by UUID.
Args:
ids: The IDs of the entries to get. Defaults to None.
where: Conditional filtering on metadata. Defaults to {}.
sort: The column to sort the entries by. Defaults to None.
limit: The maximum number of entries to return. Defaults to None.
offset: The number of entries to skip before returning. Defaults to None.
page: The page number to return. Defaults to None.
page_size: The number of entries to return per page. Defaults to None.
where_document: Conditional filtering on documents. Defaults to {}.
include: The fields to include in the response.
Defaults to ["embeddings", "metadatas", "documents"].
Returns:
GetResult: The entries in the collection that match the query.
"""
pass
| (self, collection_id: uuid.UUID, ids: Optional[List[str]] = None, where: Optional[Dict[Union[str, Literal['$and'], Literal['$or']], Union[str, int, float, bool, Dict[Union[Literal['$gt'], Literal['$gte'], Literal['$lt'], Literal['$lte'], Literal['$ne'], Literal['$eq'], Literal['$and'], Literal['$or']], Union[str, int, float, bool]], Dict[Union[Literal['$in'], Literal['$nin']], List[Union[str, int, float, bool]]], List[Dict[Union[str, Literal['$and'], Literal['$or']], Union[str, int, float, bool, Dict[Union[Literal['$gt'], Literal['$gte'], Literal['$lt'], Literal['$lte'], Literal['$ne'], Literal['$eq'], Literal['$and'], Literal['$or']], Union[str, int, float, bool]], Dict[Union[Literal['$in'], Literal['$nin']], List[Union[str, int, float, bool]]], List[ForwardRef('Where')]]]]]]] = {}, sort: Optional[str] = None, limit: Optional[int] = None, offset: Optional[int] = None, page: Optional[int] = None, page_size: Optional[int] = None, where_document: Optional[Dict[Union[Literal['$contains'], Literal['$not_contains'], Literal['$and'], Literal['$or']], Union[str, List[Dict[Union[Literal['$contains'], Literal['$not_contains'], Literal['$and'], Literal['$or']], Union[str, List[ForwardRef('WhereDocument')]]]]]]] = {}, include: List[Union[Literal['documents'], Literal['embeddings'], Literal['metadatas'], Literal['distances'], Literal['uris'], Literal['data']]] = ['embeddings', 'metadatas', 'documents']) -> chromadb.api.types.GetResult |
730,387 | chromadb.api | _modify | [Internal] Modify a collection by UUID. Can update the name and/or metadata.
Args:
id: The internal UUID of the collection to modify.
new_name: The new name of the collection.
If None, the existing name will remain. Defaults to None.
new_metadata: The new metadata to associate with the collection.
Defaults to None.
| def _modify(
self,
id: UUID,
new_name: Optional[str] = None,
new_metadata: Optional[CollectionMetadata] = None,
) -> None:
"""[Internal] Modify a collection by UUID. Can update the name and/or metadata.
Args:
id: The internal UUID of the collection to modify.
new_name: The new name of the collection.
If None, the existing name will remain. Defaults to None.
new_metadata: The new metadata to associate with the collection.
Defaults to None.
"""
pass
| (self, id: uuid.UUID, new_name: Optional[str] = None, new_metadata: Optional[Dict[str, Any]] = None) -> NoneType |
730,388 | chromadb.api | _peek | [Internal] Returns the first n entries in a collection specified by UUID.
Args:
collection_id: The UUID of the collection to peek into.
n: The number of entries to peek. Defaults to 10.
Returns:
GetResult: The first n entries in the collection.
| @abstractmethod
def _peek(self, collection_id: UUID, n: int = 10) -> GetResult:
"""[Internal] Returns the first n entries in a collection specified by UUID.
Args:
collection_id: The UUID of the collection to peek into.
n: The number of entries to peek. Defaults to 10.
Returns:
GetResult: The first n entries in the collection.
"""
pass
| (self, collection_id: uuid.UUID, n: int = 10) -> chromadb.api.types.GetResult |
730,389 | chromadb.api | _query | [Internal] Performs a nearest neighbors query on a collection specified by UUID.
Args:
collection_id: The UUID of the collection to query.
query_embeddings: The embeddings to use as the query.
n_results: The number of results to return. Defaults to 10.
where: Conditional filtering on metadata. Defaults to {}.
where_document: Conditional filtering on documents. Defaults to {}.
include: The fields to include in the response.
Defaults to ["embeddings", "metadatas", "documents", "distances"].
Returns:
QueryResult: The results of the query.
| @abstractmethod
def _query(
self,
collection_id: UUID,
query_embeddings: Embeddings,
n_results: int = 10,
where: Where = {},
where_document: WhereDocument = {},
include: Include = ["embeddings", "metadatas", "documents", "distances"],
) -> QueryResult:
"""[Internal] Performs a nearest neighbors query on a collection specified by UUID.
Args:
collection_id: The UUID of the collection to query.
query_embeddings: The embeddings to use as the query.
n_results: The number of results to return. Defaults to 10.
where: Conditional filtering on metadata. Defaults to {}.
where_document: Conditional filtering on documents. Defaults to {}.
include: The fields to include in the response.
Defaults to ["embeddings", "metadatas", "documents", "distances"].
Returns:
QueryResult: The results of the query.
"""
pass
| (self, collection_id: uuid.UUID, query_embeddings: List[Union[Sequence[float], Sequence[int]]], n_results: int = 10, where: Dict[Union[str, Literal['$and'], Literal['$or']], Union[str, int, float, bool, Dict[Union[Literal['$gt'], Literal['$gte'], Literal['$lt'], Literal['$lte'], Literal['$ne'], Literal['$eq'], Literal['$and'], Literal['$or']], Union[str, int, float, bool]], Dict[Union[Literal['$in'], Literal['$nin']], List[Union[str, int, float, bool]]], List[Dict[Union[str, Literal['$and'], Literal['$or']], Union[str, int, float, bool, Dict[Union[Literal['$gt'], Literal['$gte'], Literal['$lt'], Literal['$lte'], Literal['$ne'], Literal['$eq'], Literal['$and'], Literal['$or']], Union[str, int, float, bool]], Dict[Union[Literal['$in'], Literal['$nin']], List[Union[str, int, float, bool]]], List[ForwardRef('Where')]]]]]] = {}, where_document: Dict[Union[Literal['$contains'], Literal['$not_contains'], Literal['$and'], Literal['$or']], Union[str, List[Dict[Union[Literal['$contains'], Literal['$not_contains'], Literal['$and'], Literal['$or']], Union[str, List[ForwardRef('WhereDocument')]]]]]] = {}, include: List[Union[Literal['documents'], Literal['embeddings'], Literal['metadatas'], Literal['distances'], Literal['uris'], Literal['data']]] = ['embeddings', 'metadatas', 'documents', 'distances']) -> chromadb.api.types.QueryResult |
730,390 | chromadb.api | _update | [Internal] Update entries in a collection specified by UUID.
Args:
collection_id: The UUID of the collection to update the embeddings in.
ids: The IDs of the entries to update.
embeddings: The sequence of embeddings to update. Defaults to None.
metadatas: The metadata to associate with the embeddings. Defaults to None.
documents: The documents to associate with the embeddings. Defaults to None.
uris: URIs of data sources for each embedding. Defaults to None.
Returns:
True if the embeddings were updated successfully.
| @abstractmethod
def _update(
self,
collection_id: UUID,
ids: IDs,
embeddings: Optional[Embeddings] = None,
metadatas: Optional[Metadatas] = None,
documents: Optional[Documents] = None,
uris: Optional[URIs] = None,
) -> bool:
"""[Internal] Update entries in a collection specified by UUID.
Args:
collection_id: The UUID of the collection to update the embeddings in.
ids: The IDs of the entries to update.
embeddings: The sequence of embeddings to update. Defaults to None.
metadatas: The metadata to associate with the embeddings. Defaults to None.
documents: The documents to associate with the embeddings. Defaults to None.
uris: URIs of data sources for each embedding. Defaults to None.
Returns:
True if the embeddings were updated successfully.
"""
pass
| (self, collection_id: uuid.UUID, ids: List[str], embeddings: Optional[List[Union[Sequence[float], Sequence[int]]]] = None, metadatas: Optional[List[Mapping[str, Union[str, int, float, bool]]]] = None, documents: Optional[List[str]] = None, uris: Optional[List[str]] = None) -> bool |
730,391 | chromadb.api | _upsert | [Internal] Add or update entries in the a collection specified by UUID.
If an entry with the same id already exists, it will be updated,
otherwise it will be added.
Args:
collection_id: The collection to add the embeddings to
ids: The ids to associate with the embeddings. Defaults to None.
embeddings: The sequence of embeddings to add
metadatas: The metadata to associate with the embeddings. Defaults to None.
documents: The documents to associate with the embeddings. Defaults to None.
uris: URIs of data sources for each embedding. Defaults to None.
| @abstractmethod
def _upsert(
self,
collection_id: UUID,
ids: IDs,
embeddings: Embeddings,
metadatas: Optional[Metadatas] = None,
documents: Optional[Documents] = None,
uris: Optional[URIs] = None,
) -> bool:
"""[Internal] Add or update entries in the a collection specified by UUID.
If an entry with the same id already exists, it will be updated,
otherwise it will be added.
Args:
collection_id: The collection to add the embeddings to
ids: The ids to associate with the embeddings. Defaults to None.
embeddings: The sequence of embeddings to add
metadatas: The metadata to associate with the embeddings. Defaults to None.
documents: The documents to associate with the embeddings. Defaults to None.
uris: URIs of data sources for each embedding. Defaults to None.
"""
pass
| (self, collection_id: uuid.UUID, ids: List[str], embeddings: List[Union[Sequence[float], Sequence[int]]], metadatas: Optional[List[Mapping[str, Union[str, int, float, bool]]]] = None, documents: Optional[List[str]] = None, uris: Optional[List[str]] = None) -> bool |
730,392 | chromadb.api | clear_system_cache | Clear the system cache so that new systems can be created for an existing path.
This should only be used for testing purposes. | @staticmethod
@abstractmethod
def clear_system_cache() -> None:
"""Clear the system cache so that new systems can be created for an existing path.
This should only be used for testing purposes."""
pass
| () -> NoneType |
730,393 | chromadb.api | count_collections | Count the number of collections.
Returns:
int: The number of collections.
Examples:
```python
client.count_collections()
# 1
```
| @abstractmethod
def count_collections(self) -> int:
"""Count the number of collections.
Returns:
int: The number of collections.
Examples:
```python
client.count_collections()
# 1
```
"""
pass
| (self) -> int |
730,394 | chromadb.api | create_collection | Create a new collection with the given name and metadata.
Args:
name: The name of the collection to create.
metadata: Optional metadata to associate with the collection.
embedding_function: Optional function to use to embed documents.
Uses the default embedding function if not provided.
get_or_create: If True, return the existing collection if it exists.
data_loader: Optional function to use to load records (documents, images, etc.)
Returns:
Collection: The newly created collection.
Raises:
ValueError: If the collection already exists and get_or_create is False.
ValueError: If the collection name is invalid.
Examples:
```python
client.create_collection("my_collection")
# collection(name="my_collection", metadata={})
client.create_collection("my_collection", metadata={"foo": "bar"})
# collection(name="my_collection", metadata={"foo": "bar"})
```
| @abstractmethod
def create_collection(
self,
name: str,
metadata: Optional[CollectionMetadata] = None,
embedding_function: Optional[
EmbeddingFunction[Embeddable]
] = ef.DefaultEmbeddingFunction(), # type: ignore
data_loader: Optional[DataLoader[Loadable]] = None,
get_or_create: bool = False,
) -> Collection:
"""Create a new collection with the given name and metadata.
Args:
name: The name of the collection to create.
metadata: Optional metadata to associate with the collection.
embedding_function: Optional function to use to embed documents.
Uses the default embedding function if not provided.
get_or_create: If True, return the existing collection if it exists.
data_loader: Optional function to use to load records (documents, images, etc.)
Returns:
Collection: The newly created collection.
Raises:
ValueError: If the collection already exists and get_or_create is False.
ValueError: If the collection name is invalid.
Examples:
```python
client.create_collection("my_collection")
# collection(name="my_collection", metadata={})
client.create_collection("my_collection", metadata={"foo": "bar"})
# collection(name="my_collection", metadata={"foo": "bar"})
```
"""
pass
| (self, name: str, metadata: Optional[Dict[str, Any]] = None, embedding_function: Optional[chromadb.api.types.EmbeddingFunction[Union[List[str], List[numpy.ndarray[Any, numpy.dtype[Union[numpy.uint64, numpy.int64, numpy.float64]]]]]]] = <chromadb.utils.embedding_functions.ONNXMiniLM_L6_V2 object at 0x7fd509816bf0>, data_loader: Optional[chromadb.api.types.DataLoader[List[Optional[numpy.ndarray[Any, numpy.dtype[Union[numpy.uint64, numpy.int64, numpy.float64]]]]]]] = None, get_or_create: bool = False) -> chromadb.api.models.Collection.Collection |
730,395 | chromadb.api | delete_collection | Delete a collection with the given name.
Args:
name: The name of the collection to delete.
Raises:
ValueError: If the collection does not exist.
Examples:
```python
client.delete_collection("my_collection")
```
| @abstractmethod
def delete_collection(
self,
name: str,
) -> None:
"""Delete a collection with the given name.
Args:
name: The name of the collection to delete.
Raises:
ValueError: If the collection does not exist.
Examples:
```python
client.delete_collection("my_collection")
```
"""
pass
| (self, name: str) -> NoneType |
730,396 | chromadb.api | get_collection | Get a collection with the given name.
Args:
id: The UUID of the collection to get. Id and Name are simultaneously used for lookup if provided.
name: The name of the collection to get
embedding_function: Optional function to use to embed documents.
Uses the default embedding function if not provided.
data_loader: Optional function to use to load records (documents, images, etc.)
Returns:
Collection: The collection
Raises:
ValueError: If the collection does not exist
Examples:
```python
client.get_collection("my_collection")
# collection(name="my_collection", metadata={})
```
| @abstractmethod
def get_collection(
self,
name: str,
id: Optional[UUID] = None,
embedding_function: Optional[
EmbeddingFunction[Embeddable]
] = ef.DefaultEmbeddingFunction(), # type: ignore
data_loader: Optional[DataLoader[Loadable]] = None,
) -> Collection:
"""Get a collection with the given name.
Args:
id: The UUID of the collection to get. Id and Name are simultaneously used for lookup if provided.
name: The name of the collection to get
embedding_function: Optional function to use to embed documents.
Uses the default embedding function if not provided.
data_loader: Optional function to use to load records (documents, images, etc.)
Returns:
Collection: The collection
Raises:
ValueError: If the collection does not exist
Examples:
```python
client.get_collection("my_collection")
# collection(name="my_collection", metadata={})
```
"""
pass
| (self, name: str, id: Optional[uuid.UUID] = None, embedding_function: Optional[chromadb.api.types.EmbeddingFunction[Union[List[str], List[numpy.ndarray[Any, numpy.dtype[Union[numpy.uint64, numpy.int64, numpy.float64]]]]]]] = <chromadb.utils.embedding_functions.ONNXMiniLM_L6_V2 object at 0x7fd508c09e10>, data_loader: Optional[chromadb.api.types.DataLoader[List[Optional[numpy.ndarray[Any, numpy.dtype[Union[numpy.uint64, numpy.int64, numpy.float64]]]]]]] = None) -> chromadb.api.models.Collection.Collection |
730,397 | chromadb.api | get_or_create_collection | Get or create a collection with the given name and metadata.
Args:
name: The name of the collection to get or create
metadata: Optional metadata to associate with the collection. If
the collection alredy exists, the metadata will be updated if
provided and not None. If the collection does not exist, the
new collection will be created with the provided metadata.
embedding_function: Optional function to use to embed documents
data_loader: Optional function to use to load records (documents, images, etc.)
Returns:
The collection
Examples:
```python
client.get_or_create_collection("my_collection")
# collection(name="my_collection", metadata={})
```
| @abstractmethod
def get_or_create_collection(
self,
name: str,
metadata: Optional[CollectionMetadata] = None,
embedding_function: Optional[
EmbeddingFunction[Embeddable]
] = ef.DefaultEmbeddingFunction(), # type: ignore
data_loader: Optional[DataLoader[Loadable]] = None,
) -> Collection:
"""Get or create a collection with the given name and metadata.
Args:
name: The name of the collection to get or create
metadata: Optional metadata to associate with the collection. If
the collection alredy exists, the metadata will be updated if
provided and not None. If the collection does not exist, the
new collection will be created with the provided metadata.
embedding_function: Optional function to use to embed documents
data_loader: Optional function to use to load records (documents, images, etc.)
Returns:
The collection
Examples:
```python
client.get_or_create_collection("my_collection")
# collection(name="my_collection", metadata={})
```
"""
pass
| (self, name: str, metadata: Optional[Dict[str, Any]] = None, embedding_function: Optional[chromadb.api.types.EmbeddingFunction[Union[List[str], List[numpy.ndarray[Any, numpy.dtype[Union[numpy.uint64, numpy.int64, numpy.float64]]]]]]] = <chromadb.utils.embedding_functions.ONNXMiniLM_L6_V2 object at 0x7fd508c095a0>, data_loader: Optional[chromadb.api.types.DataLoader[List[Optional[numpy.ndarray[Any, numpy.dtype[Union[numpy.uint64, numpy.int64, numpy.float64]]]]]]] = None) -> chromadb.api.models.Collection.Collection |
730,398 | chromadb.api | get_settings | Get the settings used to initialize.
Returns:
Settings: The settings used to initialize.
| @abstractmethod
def get_settings(self) -> Settings:
"""Get the settings used to initialize.
Returns:
Settings: The settings used to initialize.
"""
pass
| (self) -> chromadb.config.Settings |
730,399 | chromadb.api | get_version | Get the version of Chroma.
Returns:
str: The version of Chroma
| @abstractmethod
def get_version(self) -> str:
"""Get the version of Chroma.
Returns:
str: The version of Chroma
"""
pass
| (self) -> str |
730,400 | chromadb.api | heartbeat | Get the current time in nanoseconds since epoch.
Used to check if the server is alive.
Returns:
int: The current time in nanoseconds since epoch
| @abstractmethod
def heartbeat(self) -> int:
"""Get the current time in nanoseconds since epoch.
Used to check if the server is alive.
Returns:
int: The current time in nanoseconds since epoch
"""
pass
| (self) -> int |
730,401 | chromadb.api | list_collections | List all collections.
Args:
limit: The maximum number of entries to return. Defaults to None.
offset: The number of entries to skip before returning. Defaults to None.
Returns:
Sequence[Collection]: A list of collections
Examples:
```python
client.list_collections()
# [collection(name="my_collection", metadata={})]
```
| @abstractmethod
def list_collections(
self,
limit: Optional[int] = None,
offset: Optional[int] = None,
) -> Sequence[Collection]:
"""List all collections.
Args:
limit: The maximum number of entries to return. Defaults to None.
offset: The number of entries to skip before returning. Defaults to None.
Returns:
Sequence[Collection]: A list of collections
Examples:
```python
client.list_collections()
# [collection(name="my_collection", metadata={})]
```
"""
pass
| (self, limit: Optional[int] = None, offset: Optional[int] = None) -> Sequence[chromadb.api.models.Collection.Collection] |
730,402 | chromadb.api | reset | Resets the database. This will delete all collections and entries.
Returns:
bool: True if the database was reset successfully.
| @abstractmethod
def reset(self) -> bool:
"""Resets the database. This will delete all collections and entries.
Returns:
bool: True if the database was reset successfully.
"""
pass
| (self) -> bool |
730,403 | chromadb.api | set_database | Set the database for the client. Raises an error if the database does not exist.
Args:
database: The database to set.
| @abstractmethod
def set_database(self, database: str) -> None:
"""Set the database for the client. Raises an error if the database does not exist.
Args:
database: The database to set.
"""
pass
| (self, database: str) -> NoneType |
730,404 | chromadb.api | set_tenant | Set the tenant and database for the client. Raises an error if the tenant or
database does not exist.
Args:
tenant: The tenant to set.
database: The database to set.
| @abstractmethod
def set_tenant(self, tenant: str, database: str = DEFAULT_DATABASE) -> None:
"""Set the tenant and database for the client. Raises an error if the tenant or
database does not exist.
Args:
tenant: The tenant to set.
database: The database to set.
"""
pass
| (self, tenant: str, database: str = 'default_database') -> NoneType |
730,405 | chromadb.api.client | Client | A client for Chroma. This is the main entrypoint for interacting with Chroma.
A client internally stores its tenant and database and proxies calls to a
Server API instance of Chroma. It treats the Server API and corresponding System
as a singleton, so multiple clients connecting to the same resource will share the
same API instance.
Client implementations should be implement their own API-caching strategies.
| class Client(SharedSystemClient, ClientAPI):
"""A client for Chroma. This is the main entrypoint for interacting with Chroma.
A client internally stores its tenant and database and proxies calls to a
Server API instance of Chroma. It treats the Server API and corresponding System
as a singleton, so multiple clients connecting to the same resource will share the
same API instance.
Client implementations should be implement their own API-caching strategies.
"""
tenant: str = DEFAULT_TENANT
database: str = DEFAULT_DATABASE
_server: ServerAPI
# An internal admin client for verifying that databases and tenants exist
_admin_client: AdminAPI
# region Initialization
def __init__(
self,
tenant: str = DEFAULT_TENANT,
database: str = DEFAULT_DATABASE,
settings: Settings = Settings(),
) -> None:
super().__init__(settings=settings)
self.tenant = tenant
self.database = database
# Create an admin client for verifying that databases and tenants exist
self._admin_client = AdminClient.from_system(self._system)
self._validate_tenant_database(tenant=tenant, database=database)
# Get the root system component we want to interact with
self._server = self._system.instance(ServerAPI)
# Submit event for a client start
telemetry_client = self._system.instance(ProductTelemetryClient)
telemetry_client.capture(ClientStartEvent())
@classmethod
@override
def from_system(
cls,
system: System,
tenant: str = DEFAULT_TENANT,
database: str = DEFAULT_DATABASE,
) -> "Client":
SharedSystemClient._populate_data_from_system(system)
instance = cls(tenant=tenant, database=database, settings=system.settings)
return instance
# endregion
# region BaseAPI Methods
# Note - we could do this in less verbose ways, but they break type checking
@override
def heartbeat(self) -> int:
return self._server.heartbeat()
@override
def list_collections(
self, limit: Optional[int] = None, offset: Optional[int] = None
) -> Sequence[Collection]:
return self._server.list_collections(
limit, offset, tenant=self.tenant, database=self.database
)
@override
def count_collections(self) -> int:
return self._server.count_collections(
tenant=self.tenant, database=self.database
)
@override
def create_collection(
self,
name: str,
metadata: Optional[CollectionMetadata] = None,
embedding_function: Optional[
EmbeddingFunction[Embeddable]
] = ef.DefaultEmbeddingFunction(), # type: ignore
data_loader: Optional[DataLoader[Loadable]] = None,
get_or_create: bool = False,
) -> Collection:
return self._server.create_collection(
name=name,
metadata=metadata,
embedding_function=embedding_function,
data_loader=data_loader,
tenant=self.tenant,
database=self.database,
get_or_create=get_or_create,
)
@override
def get_collection(
self,
name: str,
id: Optional[UUID] = None,
embedding_function: Optional[
EmbeddingFunction[Embeddable]
] = ef.DefaultEmbeddingFunction(), # type: ignore
data_loader: Optional[DataLoader[Loadable]] = None,
) -> Collection:
return self._server.get_collection(
id=id,
name=name,
embedding_function=embedding_function,
data_loader=data_loader,
tenant=self.tenant,
database=self.database,
)
@override
def get_or_create_collection(
self,
name: str,
metadata: Optional[CollectionMetadata] = None,
embedding_function: Optional[
EmbeddingFunction[Embeddable]
] = ef.DefaultEmbeddingFunction(), # type: ignore
data_loader: Optional[DataLoader[Loadable]] = None,
) -> Collection:
return self._server.get_or_create_collection(
name=name,
metadata=metadata,
embedding_function=embedding_function,
data_loader=data_loader,
tenant=self.tenant,
database=self.database,
)
@override
def _modify(
self,
id: UUID,
new_name: Optional[str] = None,
new_metadata: Optional[CollectionMetadata] = None,
) -> None:
return self._server._modify(
id=id,
new_name=new_name,
new_metadata=new_metadata,
)
@override
def delete_collection(
self,
name: str,
) -> None:
return self._server.delete_collection(
name=name,
tenant=self.tenant,
database=self.database,
)
#
# ITEM METHODS
#
@override
def _add(
self,
ids: IDs,
collection_id: UUID,
embeddings: Embeddings,
metadatas: Optional[Metadatas] = None,
documents: Optional[Documents] = None,
uris: Optional[URIs] = None,
) -> bool:
return self._server._add(
ids=ids,
collection_id=collection_id,
embeddings=embeddings,
metadatas=metadatas,
documents=documents,
uris=uris,
)
@override
def _update(
self,
collection_id: UUID,
ids: IDs,
embeddings: Optional[Embeddings] = None,
metadatas: Optional[Metadatas] = None,
documents: Optional[Documents] = None,
uris: Optional[URIs] = None,
) -> bool:
return self._server._update(
collection_id=collection_id,
ids=ids,
embeddings=embeddings,
metadatas=metadatas,
documents=documents,
uris=uris,
)
@override
def _upsert(
self,
collection_id: UUID,
ids: IDs,
embeddings: Embeddings,
metadatas: Optional[Metadatas] = None,
documents: Optional[Documents] = None,
uris: Optional[URIs] = None,
) -> bool:
return self._server._upsert(
collection_id=collection_id,
ids=ids,
embeddings=embeddings,
metadatas=metadatas,
documents=documents,
uris=uris,
)
@override
def _count(self, collection_id: UUID) -> int:
return self._server._count(
collection_id=collection_id,
)
@override
def _peek(self, collection_id: UUID, n: int = 10) -> GetResult:
return self._server._peek(
collection_id=collection_id,
n=n,
)
@override
def _get(
self,
collection_id: UUID,
ids: Optional[IDs] = None,
where: Optional[Where] = {},
sort: Optional[str] = None,
limit: Optional[int] = None,
offset: Optional[int] = None,
page: Optional[int] = None,
page_size: Optional[int] = None,
where_document: Optional[WhereDocument] = {},
include: Include = ["embeddings", "metadatas", "documents"],
) -> GetResult:
return self._server._get(
collection_id=collection_id,
ids=ids,
where=where,
sort=sort,
limit=limit,
offset=offset,
page=page,
page_size=page_size,
where_document=where_document,
include=include,
)
def _delete(
self,
collection_id: UUID,
ids: Optional[IDs],
where: Optional[Where] = {},
where_document: Optional[WhereDocument] = {},
) -> IDs:
return self._server._delete(
collection_id=collection_id,
ids=ids,
where=where,
where_document=where_document,
)
@override
def _query(
self,
collection_id: UUID,
query_embeddings: Embeddings,
n_results: int = 10,
where: Where = {},
where_document: WhereDocument = {},
include: Include = ["embeddings", "metadatas", "documents", "distances"],
) -> QueryResult:
return self._server._query(
collection_id=collection_id,
query_embeddings=query_embeddings,
n_results=n_results,
where=where,
where_document=where_document,
include=include,
)
@override
def reset(self) -> bool:
return self._server.reset()
@override
def get_version(self) -> str:
return self._server.get_version()
@override
def get_settings(self) -> Settings:
return self._server.get_settings()
@property
@override
def max_batch_size(self) -> int:
return self._server.max_batch_size
# endregion
# region ClientAPI Methods
@override
def set_tenant(self, tenant: str, database: str = DEFAULT_DATABASE) -> None:
self._validate_tenant_database(tenant=tenant, database=database)
self.tenant = tenant
self.database = database
@override
def set_database(self, database: str) -> None:
self._validate_tenant_database(tenant=self.tenant, database=database)
self.database = database
def _validate_tenant_database(self, tenant: str, database: str) -> None:
try:
self._admin_client.get_tenant(name=tenant)
except requests.exceptions.ConnectionError:
raise ValueError(
"Could not connect to a Chroma server. Are you sure it is running?"
)
# Propagate ChromaErrors
except ChromaError as e:
raise e
except Exception:
raise ValueError(
f"Could not connect to tenant {tenant}. Are you sure it exists?"
)
try:
self._admin_client.get_database(name=database, tenant=tenant)
except requests.exceptions.ConnectionError:
raise ValueError(
"Could not connect to a Chroma server. Are you sure it is running?"
)
except Exception:
raise ValueError(
f"Could not connect to database {database} for tenant {tenant}. Are you sure it exists?"
)
# endregion
| (tenant: str = 'default_tenant', database: str = 'default_database', settings: chromadb.config.Settings = Settings(environment='', chroma_api_impl='chromadb.api.segment.SegmentAPI', chroma_server_nofile=None, chroma_server_thread_pool_size=40, tenant_id='default', topic_namespace='default', chroma_server_host=None, chroma_server_headers=None, chroma_server_http_port=None, chroma_server_ssl_enabled=False, chroma_server_ssl_verify=None, chroma_server_api_default_path='/api/v1', chroma_server_cors_allow_origins=[], is_persistent=False, persist_directory='./chroma', chroma_memory_limit_bytes=0, chroma_segment_cache_policy=None, allow_reset=False, chroma_auth_token_transport_header=None, chroma_client_auth_provider=None, chroma_client_auth_credentials=None, chroma_server_auth_ignore_paths={'/api/v1': ['GET'], '/api/v1/heartbeat': ['GET'], '/api/v1/version': ['GET']}, chroma_overwrite_singleton_tenant_database_access_from_auth=False, chroma_server_authn_provider=None, chroma_server_authn_credentials=None, chroma_server_authn_credentials_file=None, chroma_server_authz_provider=None, chroma_server_authz_config=None, chroma_server_authz_config_file=None, chroma_product_telemetry_impl='chromadb.telemetry.product.posthog.Posthog', chroma_telemetry_impl='chromadb.telemetry.product.posthog.Posthog', anonymized_telemetry=True, chroma_otel_collection_endpoint='', chroma_otel_service_name='chromadb', chroma_otel_collection_headers={}, chroma_otel_granularity=None, migrations='apply', migrations_hash_algorithm='md5', chroma_segment_directory_impl='chromadb.segment.impl.distributed.segment_directory.RendezvousHashSegmentDirectory', chroma_memberlist_provider_impl='chromadb.segment.impl.distributed.segment_directory.CustomResourceMemberlistProvider', worker_memberlist_name='query-service-memberlist', chroma_server_grpc_port=None, chroma_sysdb_impl='chromadb.db.impl.sqlite.SqliteDB', chroma_producer_impl='chromadb.db.impl.sqlite.SqliteDB', chroma_consumer_impl='chromadb.db.impl.sqlite.SqliteDB', chroma_segment_manager_impl='chromadb.segment.impl.manager.local.LocalSegmentManager', chroma_quota_provider_impl=None, chroma_rate_limiting_provider_impl=None, chroma_db_impl=None, chroma_collection_assignment_policy_impl='chromadb.ingest.impl.simple_policy.SimpleAssignmentPolicy', chroma_coordinator_host='localhost', chroma_logservice_host='localhost', chroma_logservice_port=50052)) -> None |
730,406 | chromadb.api.client | __init__ | null | def __init__(
self,
tenant: str = DEFAULT_TENANT,
database: str = DEFAULT_DATABASE,
settings: Settings = Settings(),
) -> None:
super().__init__(settings=settings)
self.tenant = tenant
self.database = database
# Create an admin client for verifying that databases and tenants exist
self._admin_client = AdminClient.from_system(self._system)
self._validate_tenant_database(tenant=tenant, database=database)
# Get the root system component we want to interact with
self._server = self._system.instance(ServerAPI)
# Submit event for a client start
telemetry_client = self._system.instance(ProductTelemetryClient)
telemetry_client.capture(ClientStartEvent())
| (self, tenant: str = 'default_tenant', database: str = 'default_database', settings: chromadb.config.Settings = Settings(environment='', chroma_api_impl='chromadb.api.segment.SegmentAPI', chroma_server_nofile=None, chroma_server_thread_pool_size=40, tenant_id='default', topic_namespace='default', chroma_server_host=None, chroma_server_headers=None, chroma_server_http_port=None, chroma_server_ssl_enabled=False, chroma_server_ssl_verify=None, chroma_server_api_default_path='/api/v1', chroma_server_cors_allow_origins=[], is_persistent=False, persist_directory='./chroma', chroma_memory_limit_bytes=0, chroma_segment_cache_policy=None, allow_reset=False, chroma_auth_token_transport_header=None, chroma_client_auth_provider=None, chroma_client_auth_credentials=None, chroma_server_auth_ignore_paths={'/api/v1': ['GET'], '/api/v1/heartbeat': ['GET'], '/api/v1/version': ['GET']}, chroma_overwrite_singleton_tenant_database_access_from_auth=False, chroma_server_authn_provider=None, chroma_server_authn_credentials=None, chroma_server_authn_credentials_file=None, chroma_server_authz_provider=None, chroma_server_authz_config=None, chroma_server_authz_config_file=None, chroma_product_telemetry_impl='chromadb.telemetry.product.posthog.Posthog', chroma_telemetry_impl='chromadb.telemetry.product.posthog.Posthog', anonymized_telemetry=True, chroma_otel_collection_endpoint='', chroma_otel_service_name='chromadb', chroma_otel_collection_headers={}, chroma_otel_granularity=None, migrations='apply', migrations_hash_algorithm='md5', chroma_segment_directory_impl='chromadb.segment.impl.distributed.segment_directory.RendezvousHashSegmentDirectory', chroma_memberlist_provider_impl='chromadb.segment.impl.distributed.segment_directory.CustomResourceMemberlistProvider', worker_memberlist_name='query-service-memberlist', chroma_server_grpc_port=None, chroma_sysdb_impl='chromadb.db.impl.sqlite.SqliteDB', chroma_producer_impl='chromadb.db.impl.sqlite.SqliteDB', chroma_consumer_impl='chromadb.db.impl.sqlite.SqliteDB', chroma_segment_manager_impl='chromadb.segment.impl.manager.local.LocalSegmentManager', chroma_quota_provider_impl=None, chroma_rate_limiting_provider_impl=None, chroma_db_impl=None, chroma_collection_assignment_policy_impl='chromadb.ingest.impl.simple_policy.SimpleAssignmentPolicy', chroma_coordinator_host='localhost', chroma_logservice_host='localhost', chroma_logservice_port=50052)) -> NoneType |
730,407 | chromadb.api.client | _add | [Internal] Add embeddings to a collection specified by UUID.
If (some) ids already exist, only the new embeddings will be added.
Args:
ids: The ids to associate with the embeddings.
collection_id: The UUID of the collection to add the embeddings to.
embedding: The sequence of embeddings to add.
metadata: The metadata to associate with the embeddings. Defaults to None.
documents: The documents to associate with the embeddings. Defaults to None.
uris: URIs of data sources for each embedding. Defaults to None.
Returns:
True if the embeddings were added successfully.
| @override
def _add(
self,
ids: IDs,
collection_id: UUID,
embeddings: Embeddings,
metadatas: Optional[Metadatas] = None,
documents: Optional[Documents] = None,
uris: Optional[URIs] = None,
) -> bool:
return self._server._add(
ids=ids,
collection_id=collection_id,
embeddings=embeddings,
metadatas=metadatas,
documents=documents,
uris=uris,
)
| (self, ids: List[str], collection_id: uuid.UUID, embeddings: List[Union[Sequence[float], Sequence[int]]], metadatas: Optional[List[Mapping[str, Union[str, int, float, bool]]]] = None, documents: Optional[List[str]] = None, uris: Optional[List[str]] = None) -> bool |
730,408 | chromadb.api.client | _count | [Internal] Returns the number of entries in a collection specified by UUID.
Args:
collection_id: The UUID of the collection to count the embeddings in.
Returns:
int: The number of embeddings in the collection
| @override
def _count(self, collection_id: UUID) -> int:
return self._server._count(
collection_id=collection_id,
)
| (self, collection_id: uuid.UUID) -> int |
730,409 | chromadb.api.client | _delete | null | def _delete(
self,
collection_id: UUID,
ids: Optional[IDs],
where: Optional[Where] = {},
where_document: Optional[WhereDocument] = {},
) -> IDs:
return self._server._delete(
collection_id=collection_id,
ids=ids,
where=where,
where_document=where_document,
)
| (self, collection_id: uuid.UUID, ids: Optional[List[str]], where: Optional[Dict[Union[str, Literal['$and'], Literal['$or']], Union[str, int, float, bool, Dict[Union[Literal['$gt'], Literal['$gte'], Literal['$lt'], Literal['$lte'], Literal['$ne'], Literal['$eq'], Literal['$and'], Literal['$or']], Union[str, int, float, bool]], Dict[Union[Literal['$in'], Literal['$nin']], List[Union[str, int, float, bool]]], List[Dict[Union[str, Literal['$and'], Literal['$or']], Union[str, int, float, bool, Dict[Union[Literal['$gt'], Literal['$gte'], Literal['$lt'], Literal['$lte'], Literal['$ne'], Literal['$eq'], Literal['$and'], Literal['$or']], Union[str, int, float, bool]], Dict[Union[Literal['$in'], Literal['$nin']], List[Union[str, int, float, bool]]], List[ForwardRef('Where')]]]]]]] = {}, where_document: Optional[Dict[Union[Literal['$contains'], Literal['$not_contains'], Literal['$and'], Literal['$or']], Union[str, List[Dict[Union[Literal['$contains'], Literal['$not_contains'], Literal['$and'], Literal['$or']], Union[str, List[ForwardRef('WhereDocument')]]]]]]] = {}) -> List[str] |
730,410 | chromadb.api.client | _get | [Internal] Returns entries from a collection specified by UUID.
Args:
ids: The IDs of the entries to get. Defaults to None.
where: Conditional filtering on metadata. Defaults to {}.
sort: The column to sort the entries by. Defaults to None.
limit: The maximum number of entries to return. Defaults to None.
offset: The number of entries to skip before returning. Defaults to None.
page: The page number to return. Defaults to None.
page_size: The number of entries to return per page. Defaults to None.
where_document: Conditional filtering on documents. Defaults to {}.
include: The fields to include in the response.
Defaults to ["embeddings", "metadatas", "documents"].
Returns:
GetResult: The entries in the collection that match the query.
| @override
def _get(
self,
collection_id: UUID,
ids: Optional[IDs] = None,
where: Optional[Where] = {},
sort: Optional[str] = None,
limit: Optional[int] = None,
offset: Optional[int] = None,
page: Optional[int] = None,
page_size: Optional[int] = None,
where_document: Optional[WhereDocument] = {},
include: Include = ["embeddings", "metadatas", "documents"],
) -> GetResult:
return self._server._get(
collection_id=collection_id,
ids=ids,
where=where,
sort=sort,
limit=limit,
offset=offset,
page=page,
page_size=page_size,
where_document=where_document,
include=include,
)
| (self, collection_id: uuid.UUID, ids: Optional[List[str]] = None, where: Optional[Dict[Union[str, Literal['$and'], Literal['$or']], Union[str, int, float, bool, Dict[Union[Literal['$gt'], Literal['$gte'], Literal['$lt'], Literal['$lte'], Literal['$ne'], Literal['$eq'], Literal['$and'], Literal['$or']], Union[str, int, float, bool]], Dict[Union[Literal['$in'], Literal['$nin']], List[Union[str, int, float, bool]]], List[Dict[Union[str, Literal['$and'], Literal['$or']], Union[str, int, float, bool, Dict[Union[Literal['$gt'], Literal['$gte'], Literal['$lt'], Literal['$lte'], Literal['$ne'], Literal['$eq'], Literal['$and'], Literal['$or']], Union[str, int, float, bool]], Dict[Union[Literal['$in'], Literal['$nin']], List[Union[str, int, float, bool]]], List[ForwardRef('Where')]]]]]]] = {}, sort: Optional[str] = None, limit: Optional[int] = None, offset: Optional[int] = None, page: Optional[int] = None, page_size: Optional[int] = None, where_document: Optional[Dict[Union[Literal['$contains'], Literal['$not_contains'], Literal['$and'], Literal['$or']], Union[str, List[Dict[Union[Literal['$contains'], Literal['$not_contains'], Literal['$and'], Literal['$or']], Union[str, List[ForwardRef('WhereDocument')]]]]]]] = {}, include: List[Union[Literal['documents'], Literal['embeddings'], Literal['metadatas'], Literal['distances'], Literal['uris'], Literal['data']]] = ['embeddings', 'metadatas', 'documents']) -> chromadb.api.types.GetResult |
730,412 | chromadb.api.client | _modify | [Internal] Modify a collection by UUID. Can update the name and/or metadata.
Args:
id: The internal UUID of the collection to modify.
new_name: The new name of the collection.
If None, the existing name will remain. Defaults to None.
new_metadata: The new metadata to associate with the collection.
Defaults to None.
| @override
def _modify(
self,
id: UUID,
new_name: Optional[str] = None,
new_metadata: Optional[CollectionMetadata] = None,
) -> None:
return self._server._modify(
id=id,
new_name=new_name,
new_metadata=new_metadata,
)
| (self, id: uuid.UUID, new_name: Optional[str] = None, new_metadata: Optional[Dict[str, Any]] = None) -> NoneType |
730,413 | chromadb.api.client | _peek | [Internal] Returns the first n entries in a collection specified by UUID.
Args:
collection_id: The UUID of the collection to peek into.
n: The number of entries to peek. Defaults to 10.
Returns:
GetResult: The first n entries in the collection.
| @override
def _peek(self, collection_id: UUID, n: int = 10) -> GetResult:
return self._server._peek(
collection_id=collection_id,
n=n,
)
| (self, collection_id: uuid.UUID, n: int = 10) -> chromadb.api.types.GetResult |
730,415 | chromadb.api.client | _query | [Internal] Performs a nearest neighbors query on a collection specified by UUID.
Args:
collection_id: The UUID of the collection to query.
query_embeddings: The embeddings to use as the query.
n_results: The number of results to return. Defaults to 10.
where: Conditional filtering on metadata. Defaults to {}.
where_document: Conditional filtering on documents. Defaults to {}.
include: The fields to include in the response.
Defaults to ["embeddings", "metadatas", "documents", "distances"].
Returns:
QueryResult: The results of the query.
| @override
def _query(
self,
collection_id: UUID,
query_embeddings: Embeddings,
n_results: int = 10,
where: Where = {},
where_document: WhereDocument = {},
include: Include = ["embeddings", "metadatas", "documents", "distances"],
) -> QueryResult:
return self._server._query(
collection_id=collection_id,
query_embeddings=query_embeddings,
n_results=n_results,
where=where,
where_document=where_document,
include=include,
)
| (self, collection_id: uuid.UUID, query_embeddings: List[Union[Sequence[float], Sequence[int]]], n_results: int = 10, where: Dict[Union[str, Literal['$and'], Literal['$or']], Union[str, int, float, bool, Dict[Union[Literal['$gt'], Literal['$gte'], Literal['$lt'], Literal['$lte'], Literal['$ne'], Literal['$eq'], Literal['$and'], Literal['$or']], Union[str, int, float, bool]], Dict[Union[Literal['$in'], Literal['$nin']], List[Union[str, int, float, bool]]], List[Dict[Union[str, Literal['$and'], Literal['$or']], Union[str, int, float, bool, Dict[Union[Literal['$gt'], Literal['$gte'], Literal['$lt'], Literal['$lte'], Literal['$ne'], Literal['$eq'], Literal['$and'], Literal['$or']], Union[str, int, float, bool]], Dict[Union[Literal['$in'], Literal['$nin']], List[Union[str, int, float, bool]]], List[ForwardRef('Where')]]]]]] = {}, where_document: Dict[Union[Literal['$contains'], Literal['$not_contains'], Literal['$and'], Literal['$or']], Union[str, List[Dict[Union[Literal['$contains'], Literal['$not_contains'], Literal['$and'], Literal['$or']], Union[str, List[ForwardRef('WhereDocument')]]]]]] = {}, include: List[Union[Literal['documents'], Literal['embeddings'], Literal['metadatas'], Literal['distances'], Literal['uris'], Literal['data']]] = ['embeddings', 'metadatas', 'documents', 'distances']) -> chromadb.api.types.QueryResult |
730,416 | chromadb.api.client | _update | [Internal] Update entries in a collection specified by UUID.
Args:
collection_id: The UUID of the collection to update the embeddings in.
ids: The IDs of the entries to update.
embeddings: The sequence of embeddings to update. Defaults to None.
metadatas: The metadata to associate with the embeddings. Defaults to None.
documents: The documents to associate with the embeddings. Defaults to None.
uris: URIs of data sources for each embedding. Defaults to None.
Returns:
True if the embeddings were updated successfully.
| @override
def _update(
self,
collection_id: UUID,
ids: IDs,
embeddings: Optional[Embeddings] = None,
metadatas: Optional[Metadatas] = None,
documents: Optional[Documents] = None,
uris: Optional[URIs] = None,
) -> bool:
return self._server._update(
collection_id=collection_id,
ids=ids,
embeddings=embeddings,
metadatas=metadatas,
documents=documents,
uris=uris,
)
| (self, collection_id: uuid.UUID, ids: List[str], embeddings: Optional[List[Union[Sequence[float], Sequence[int]]]] = None, metadatas: Optional[List[Mapping[str, Union[str, int, float, bool]]]] = None, documents: Optional[List[str]] = None, uris: Optional[List[str]] = None) -> bool |
730,417 | chromadb.api.client | _upsert | [Internal] Add or update entries in the a collection specified by UUID.
If an entry with the same id already exists, it will be updated,
otherwise it will be added.
Args:
collection_id: The collection to add the embeddings to
ids: The ids to associate with the embeddings. Defaults to None.
embeddings: The sequence of embeddings to add
metadatas: The metadata to associate with the embeddings. Defaults to None.
documents: The documents to associate with the embeddings. Defaults to None.
uris: URIs of data sources for each embedding. Defaults to None.
| @override
def _upsert(
self,
collection_id: UUID,
ids: IDs,
embeddings: Embeddings,
metadatas: Optional[Metadatas] = None,
documents: Optional[Documents] = None,
uris: Optional[URIs] = None,
) -> bool:
return self._server._upsert(
collection_id=collection_id,
ids=ids,
embeddings=embeddings,
metadatas=metadatas,
documents=documents,
uris=uris,
)
| (self, collection_id: uuid.UUID, ids: List[str], embeddings: List[Union[Sequence[float], Sequence[int]]], metadatas: Optional[List[Mapping[str, Union[str, int, float, bool]]]] = None, documents: Optional[List[str]] = None, uris: Optional[List[str]] = None) -> bool |
730,418 | chromadb.api.client | _validate_tenant_database | null | def _validate_tenant_database(self, tenant: str, database: str) -> None:
try:
self._admin_client.get_tenant(name=tenant)
except requests.exceptions.ConnectionError:
raise ValueError(
"Could not connect to a Chroma server. Are you sure it is running?"
)
# Propagate ChromaErrors
except ChromaError as e:
raise e
except Exception:
raise ValueError(
f"Could not connect to tenant {tenant}. Are you sure it exists?"
)
try:
self._admin_client.get_database(name=database, tenant=tenant)
except requests.exceptions.ConnectionError:
raise ValueError(
"Could not connect to a Chroma server. Are you sure it is running?"
)
except Exception:
raise ValueError(
f"Could not connect to database {database} for tenant {tenant}. Are you sure it exists?"
)
| (self, tenant: str, database: str) -> NoneType |
730,420 | chromadb.api.client | count_collections | Count the number of collections.
Returns:
int: The number of collections.
Examples:
```python
client.count_collections()
# 1
```
| @override
def count_collections(self) -> int:
return self._server.count_collections(
tenant=self.tenant, database=self.database
)
| (self) -> int |
730,421 | chromadb.api.client | create_collection | Create a new collection with the given name and metadata.
Args:
name: The name of the collection to create.
metadata: Optional metadata to associate with the collection.
embedding_function: Optional function to use to embed documents.
Uses the default embedding function if not provided.
get_or_create: If True, return the existing collection if it exists.
data_loader: Optional function to use to load records (documents, images, etc.)
Returns:
Collection: The newly created collection.
Raises:
ValueError: If the collection already exists and get_or_create is False.
ValueError: If the collection name is invalid.
Examples:
```python
client.create_collection("my_collection")
# collection(name="my_collection", metadata={})
client.create_collection("my_collection", metadata={"foo": "bar"})
# collection(name="my_collection", metadata={"foo": "bar"})
```
| @override
def create_collection(
self,
name: str,
metadata: Optional[CollectionMetadata] = None,
embedding_function: Optional[
EmbeddingFunction[Embeddable]
] = ef.DefaultEmbeddingFunction(), # type: ignore
data_loader: Optional[DataLoader[Loadable]] = None,
get_or_create: bool = False,
) -> Collection:
return self._server.create_collection(
name=name,
metadata=metadata,
embedding_function=embedding_function,
data_loader=data_loader,
tenant=self.tenant,
database=self.database,
get_or_create=get_or_create,
)
| (self, name: str, metadata: Optional[Dict[str, Any]] = None, embedding_function: Optional[chromadb.api.types.EmbeddingFunction[Union[List[str], List[numpy.ndarray[Any, numpy.dtype[Union[numpy.uint64, numpy.int64, numpy.float64]]]]]]] = <chromadb.utils.embedding_functions.ONNXMiniLM_L6_V2 object at 0x7fd508aebee0>, data_loader: Optional[chromadb.api.types.DataLoader[List[Optional[numpy.ndarray[Any, numpy.dtype[Union[numpy.uint64, numpy.int64, numpy.float64]]]]]]] = None, get_or_create: bool = False) -> chromadb.api.models.Collection.Collection |
730,422 | chromadb.api.client | delete_collection | Delete a collection with the given name.
Args:
name: The name of the collection to delete.
Raises:
ValueError: If the collection does not exist.
Examples:
```python
client.delete_collection("my_collection")
```
| @override
def delete_collection(
self,
name: str,
) -> None:
return self._server.delete_collection(
name=name,
tenant=self.tenant,
database=self.database,
)
| (self, name: str) -> NoneType |
730,423 | chromadb.api.client | get_collection | Get a collection with the given name.
Args:
id: The UUID of the collection to get. Id and Name are simultaneously used for lookup if provided.
name: The name of the collection to get
embedding_function: Optional function to use to embed documents.
Uses the default embedding function if not provided.
data_loader: Optional function to use to load records (documents, images, etc.)
Returns:
Collection: The collection
Raises:
ValueError: If the collection does not exist
Examples:
```python
client.get_collection("my_collection")
# collection(name="my_collection", metadata={})
```
| @override
def get_collection(
self,
name: str,
id: Optional[UUID] = None,
embedding_function: Optional[
EmbeddingFunction[Embeddable]
] = ef.DefaultEmbeddingFunction(), # type: ignore
data_loader: Optional[DataLoader[Loadable]] = None,
) -> Collection:
return self._server.get_collection(
id=id,
name=name,
embedding_function=embedding_function,
data_loader=data_loader,
tenant=self.tenant,
database=self.database,
)
| (self, name: str, id: Optional[uuid.UUID] = None, embedding_function: Optional[chromadb.api.types.EmbeddingFunction[Union[List[str], List[numpy.ndarray[Any, numpy.dtype[Union[numpy.uint64, numpy.int64, numpy.float64]]]]]]] = <chromadb.utils.embedding_functions.ONNXMiniLM_L6_V2 object at 0x7fd509048d30>, data_loader: Optional[chromadb.api.types.DataLoader[List[Optional[numpy.ndarray[Any, numpy.dtype[Union[numpy.uint64, numpy.int64, numpy.float64]]]]]]] = None) -> chromadb.api.models.Collection.Collection |
730,424 | chromadb.api.client | get_or_create_collection | Get or create a collection with the given name and metadata.
Args:
name: The name of the collection to get or create
metadata: Optional metadata to associate with the collection. If
the collection alredy exists, the metadata will be updated if
provided and not None. If the collection does not exist, the
new collection will be created with the provided metadata.
embedding_function: Optional function to use to embed documents
data_loader: Optional function to use to load records (documents, images, etc.)
Returns:
The collection
Examples:
```python
client.get_or_create_collection("my_collection")
# collection(name="my_collection", metadata={})
```
| @override
def get_or_create_collection(
self,
name: str,
metadata: Optional[CollectionMetadata] = None,
embedding_function: Optional[
EmbeddingFunction[Embeddable]
] = ef.DefaultEmbeddingFunction(), # type: ignore
data_loader: Optional[DataLoader[Loadable]] = None,
) -> Collection:
return self._server.get_or_create_collection(
name=name,
metadata=metadata,
embedding_function=embedding_function,
data_loader=data_loader,
tenant=self.tenant,
database=self.database,
)
| (self, name: str, metadata: Optional[Dict[str, Any]] = None, embedding_function: Optional[chromadb.api.types.EmbeddingFunction[Union[List[str], List[numpy.ndarray[Any, numpy.dtype[Union[numpy.uint64, numpy.int64, numpy.float64]]]]]]] = <chromadb.utils.embedding_functions.ONNXMiniLM_L6_V2 object at 0x7fd508ae9840>, data_loader: Optional[chromadb.api.types.DataLoader[List[Optional[numpy.ndarray[Any, numpy.dtype[Union[numpy.uint64, numpy.int64, numpy.float64]]]]]]] = None) -> chromadb.api.models.Collection.Collection |
730,425 | chromadb.api.client | get_settings | Get the settings used to initialize.
Returns:
Settings: The settings used to initialize.
| @override
def get_settings(self) -> Settings:
return self._server.get_settings()
| (self) -> chromadb.config.Settings |
730,426 | chromadb.api.client | get_version | Get the version of Chroma.
Returns:
str: The version of Chroma
| @override
def get_version(self) -> str:
return self._server.get_version()
| (self) -> str |
730,427 | chromadb.api.client | heartbeat | Get the current time in nanoseconds since epoch.
Used to check if the server is alive.
Returns:
int: The current time in nanoseconds since epoch
| @override
def heartbeat(self) -> int:
return self._server.heartbeat()
| (self) -> int |
730,428 | chromadb.api.client | list_collections | List all collections.
Args:
limit: The maximum number of entries to return. Defaults to None.
offset: The number of entries to skip before returning. Defaults to None.
Returns:
Sequence[Collection]: A list of collections
Examples:
```python
client.list_collections()
# [collection(name="my_collection", metadata={})]
```
| @override
def list_collections(
self, limit: Optional[int] = None, offset: Optional[int] = None
) -> Sequence[Collection]:
return self._server.list_collections(
limit, offset, tenant=self.tenant, database=self.database
)
| (self, limit: Optional[int] = None, offset: Optional[int] = None) -> Sequence[chromadb.api.models.Collection.Collection] |
730,429 | chromadb.api.client | reset | Resets the database. This will delete all collections and entries.
Returns:
bool: True if the database was reset successfully.
| @override
def reset(self) -> bool:
return self._server.reset()
| (self) -> bool |
730,430 | chromadb.api.client | set_database | Set the database for the client. Raises an error if the database does not exist.
Args:
database: The database to set.
| @override
def set_database(self, database: str) -> None:
self._validate_tenant_database(tenant=self.tenant, database=database)
self.database = database
| (self, database: str) -> NoneType |
730,431 | chromadb.api.client | set_tenant | Set the tenant and database for the client. Raises an error if the tenant or
database does not exist.
Args:
tenant: The tenant to set.
database: The database to set.
| @override
def set_tenant(self, tenant: str, database: str = DEFAULT_DATABASE) -> None:
self._validate_tenant_database(tenant=tenant, database=database)
self.tenant = tenant
self.database = database
| (self, tenant: str, database: str = 'default_database') -> NoneType |
730,432 | chromadb | CloudClient |
Creates a client to connect to a tennant and database on the Chroma cloud.
Args:
tenant: The tenant to use for this client.
database: The database to use for this client.
api_key: The api key to use for this client.
| def CloudClient(
tenant: str,
database: str,
api_key: Optional[str] = None,
settings: Optional[Settings] = None,
*, # Following arguments are keyword-only, intended for testing only.
cloud_host: str = "api.trychroma.com",
cloud_port: int = 8000,
enable_ssl: bool = True,
) -> ClientAPI:
"""
Creates a client to connect to a tennant and database on the Chroma cloud.
Args:
tenant: The tenant to use for this client.
database: The database to use for this client.
api_key: The api key to use for this client.
"""
# If no API key is provided, try to load it from the environment variable
if api_key is None:
import os
api_key = os.environ.get("CHROMA_API_KEY")
# If the API key is still not provided, prompt the user
if api_key is None:
print(
"\033[93mDon't have an API key?\033[0m Get one at https://app.trychroma.com"
)
api_key = input("Please enter your Chroma API key: ")
if settings is None:
settings = Settings()
# Make sure paramaters are the correct types -- users can pass anything.
tenant = str(tenant)
database = str(database)
api_key = str(api_key)
cloud_host = str(cloud_host)
cloud_port = int(cloud_port)
enable_ssl = bool(enable_ssl)
settings.chroma_api_impl = "chromadb.api.fastapi.FastAPI"
settings.chroma_server_host = cloud_host
settings.chroma_server_http_port = cloud_port
# Always use SSL for cloud
settings.chroma_server_ssl_enabled = enable_ssl
settings.chroma_client_auth_provider = "chromadb.auth.token_authn.TokenAuthClientProvider"
settings.chroma_client_auth_credentials = api_key
settings.chroma_auth_token_transport_header = (
TokenTransportHeader.X_CHROMA_TOKEN.name
)
return ClientCreator(tenant=tenant, database=database, settings=settings)
| (tenant: str, database: str, api_key: Optional[str] = None, settings: Optional[chromadb.config.Settings] = None, *, cloud_host: str = 'api.trychroma.com', cloud_port: int = 8000, enable_ssl: bool = True) -> chromadb.api.ClientAPI |
730,433 | chromadb.api.models.Collection | Collection | null | class Collection(BaseModel):
name: str
id: UUID
metadata: Optional[CollectionMetadata] = None
tenant: Optional[str] = None
database: Optional[str] = None
_client: "ServerAPI" = PrivateAttr()
_embedding_function: Optional[EmbeddingFunction[Embeddable]] = PrivateAttr()
_data_loader: Optional[DataLoader[Loadable]] = PrivateAttr()
def __init__(
self,
client: "ServerAPI",
name: str,
id: UUID,
embedding_function: Optional[
EmbeddingFunction[Embeddable]
] = ef.DefaultEmbeddingFunction(), # type: ignore
data_loader: Optional[DataLoader[Loadable]] = None,
tenant: Optional[str] = None,
database: Optional[str] = None,
metadata: Optional[CollectionMetadata] = None,
):
super().__init__(
name=name, metadata=metadata, id=id, tenant=tenant, database=database
)
self._client = client
# Check to make sure the embedding function has the right signature, as defined by the EmbeddingFunction protocol
if embedding_function is not None:
validate_embedding_function(embedding_function)
self._embedding_function = embedding_function
self._data_loader = data_loader
def __repr__(self) -> str:
return f"Collection(name={self.name})"
def count(self) -> int:
"""The total number of embeddings added to the database
Returns:
int: The total number of embeddings added to the database
"""
return self._client._count(collection_id=self.id)
def add(
self,
ids: OneOrMany[ID],
embeddings: Optional[
Union[
OneOrMany[Embedding],
OneOrMany[np.ndarray],
]
] = None,
metadatas: Optional[OneOrMany[Metadata]] = None,
documents: Optional[OneOrMany[Document]] = None,
images: Optional[OneOrMany[Image]] = None,
uris: Optional[OneOrMany[URI]] = None,
) -> None:
"""Add embeddings to the data store.
Args:
ids: The ids of the embeddings you wish to add
embeddings: The embeddings to add. If None, embeddings will be computed based on the documents or images using the embedding_function set for the Collection. Optional.
metadatas: The metadata to associate with the embeddings. When querying, you can filter on this metadata. Optional.
documents: The documents to associate with the embeddings. Optional.
images: The images to associate with the embeddings. Optional.
uris: The uris of the images to associate with the embeddings. Optional.
Returns:
None
Raises:
ValueError: If you don't provide either embeddings or documents
ValueError: If the length of ids, embeddings, metadatas, or documents don't match
ValueError: If you don't provide an embedding function and don't provide embeddings
ValueError: If you provide both embeddings and documents
ValueError: If you provide an id that already exists
"""
(
ids,
embeddings,
metadatas,
documents,
images,
uris,
) = self._validate_embedding_set(
ids, embeddings, metadatas, documents, images, uris
)
# We need to compute the embeddings if they're not provided
if embeddings is None:
# At this point, we know that one of documents or images are provided from the validation above
if documents is not None:
embeddings = self._embed(input=documents)
elif images is not None:
embeddings = self._embed(input=images)
else:
if uris is None:
raise ValueError(
"You must provide either embeddings, documents, images, or uris."
)
if self._data_loader is None:
raise ValueError(
"You must set a data loader on the collection if loading from URIs."
)
embeddings = self._embed(self._data_loader(uris))
self._client._add(ids, self.id, embeddings, metadatas, documents, uris)
def get(
self,
ids: Optional[OneOrMany[ID]] = None,
where: Optional[Where] = None,
limit: Optional[int] = None,
offset: Optional[int] = None,
where_document: Optional[WhereDocument] = None,
include: Include = ["metadatas", "documents"],
) -> GetResult:
"""Get embeddings and their associate data from the data store. If no ids or where filter is provided returns
all embeddings up to limit starting at offset.
Args:
ids: The ids of the embeddings to get. Optional.
where: A Where type dict used to filter results by. E.g. `{"$and": ["color" : "red", "price": {"$gte": 4.20}]}`. Optional.
limit: The number of documents to return. Optional.
offset: The offset to start returning results from. Useful for paging results with limit. Optional.
where_document: A WhereDocument type dict used to filter by the documents. E.g. `{$contains: {"text": "hello"}}`. Optional.
include: A list of what to include in the results. Can contain `"embeddings"`, `"metadatas"`, `"documents"`. Ids are always included. Defaults to `["metadatas", "documents"]`. Optional.
Returns:
GetResult: A GetResult object containing the results.
"""
valid_where = validate_where(where) if where else None
valid_where_document = (
validate_where_document(where_document) if where_document else None
)
valid_ids = validate_ids(maybe_cast_one_to_many_ids(ids)) if ids else None
valid_include = validate_include(include, allow_distances=False)
if "data" in include and self._data_loader is None:
raise ValueError(
"You must set a data loader on the collection if loading from URIs."
)
# We need to include uris in the result from the API to load datas
if "data" in include and "uris" not in include:
valid_include.append("uris")
get_results = self._client._get(
self.id,
valid_ids,
valid_where,
None,
limit,
offset,
where_document=valid_where_document,
include=valid_include,
)
if (
"data" in include
and self._data_loader is not None
and get_results["uris"] is not None
):
get_results["data"] = self._data_loader(get_results["uris"])
# Remove URIs from the result if they weren't requested
if "uris" not in include:
get_results["uris"] = None
return get_results
def peek(self, limit: int = 10) -> GetResult:
"""Get the first few results in the database up to limit
Args:
limit: The number of results to return.
Returns:
GetResult: A GetResult object containing the results.
"""
return self._client._peek(self.id, limit)
def query(
self,
query_embeddings: Optional[
Union[
OneOrMany[Embedding],
OneOrMany[np.ndarray],
]
] = None,
query_texts: Optional[OneOrMany[Document]] = None,
query_images: Optional[OneOrMany[Image]] = None,
query_uris: Optional[OneOrMany[URI]] = None,
n_results: int = 10,
where: Optional[Where] = None,
where_document: Optional[WhereDocument] = None,
include: Include = ["metadatas", "documents", "distances"],
) -> QueryResult:
"""Get the n_results nearest neighbor embeddings for provided query_embeddings or query_texts.
Args:
query_embeddings: The embeddings to get the closes neighbors of. Optional.
query_texts: The document texts to get the closes neighbors of. Optional.
query_images: The images to get the closes neighbors of. Optional.
n_results: The number of neighbors to return for each query_embedding or query_texts. Optional.
where: A Where type dict used to filter results by. E.g. `{"$and": ["color" : "red", "price": {"$gte": 4.20}]}`. Optional.
where_document: A WhereDocument type dict used to filter by the documents. E.g. `{$contains: {"text": "hello"}}`. Optional.
include: A list of what to include in the results. Can contain `"embeddings"`, `"metadatas"`, `"documents"`, `"distances"`. Ids are always included. Defaults to `["metadatas", "documents", "distances"]`. Optional.
Returns:
QueryResult: A QueryResult object containing the results.
Raises:
ValueError: If you don't provide either query_embeddings, query_texts, or query_images
ValueError: If you provide both query_embeddings and query_texts
ValueError: If you provide both query_embeddings and query_images
ValueError: If you provide both query_texts and query_images
"""
# Users must provide only one of query_embeddings, query_texts, query_images, or query_uris
if not (
(query_embeddings is not None)
^ (query_texts is not None)
^ (query_images is not None)
^ (query_uris is not None)
):
raise ValueError(
"You must provide one of query_embeddings, query_texts, query_images, or query_uris."
)
valid_where = validate_where(where) if where else {}
valid_where_document = (
validate_where_document(where_document) if where_document else {}
)
valid_query_embeddings = (
validate_embeddings(
self._normalize_embeddings(
maybe_cast_one_to_many_embedding(query_embeddings)
)
)
if query_embeddings is not None
else None
)
valid_query_texts = (
maybe_cast_one_to_many_document(query_texts)
if query_texts is not None
else None
)
valid_query_images = (
maybe_cast_one_to_many_image(query_images)
if query_images is not None
else None
)
valid_query_uris = (
maybe_cast_one_to_many_uri(query_uris) if query_uris is not None else None
)
valid_include = validate_include(include, allow_distances=True)
valid_n_results = validate_n_results(n_results)
# If query_embeddings are not provided, we need to compute them from the inputs
if valid_query_embeddings is None:
if query_texts is not None:
valid_query_embeddings = self._embed(input=valid_query_texts)
elif query_images is not None:
valid_query_embeddings = self._embed(input=valid_query_images)
else:
if valid_query_uris is None:
raise ValueError(
"You must provide either query_embeddings, query_texts, query_images, or query_uris."
)
if self._data_loader is None:
raise ValueError(
"You must set a data loader on the collection if loading from URIs."
)
valid_query_embeddings = self._embed(
self._data_loader(valid_query_uris)
)
if "data" in include and "uris" not in include:
valid_include.append("uris")
query_results = self._client._query(
collection_id=self.id,
query_embeddings=valid_query_embeddings,
n_results=valid_n_results,
where=valid_where,
where_document=valid_where_document,
include=include,
)
if (
"data" in include
and self._data_loader is not None
and query_results["uris"] is not None
):
query_results["data"] = [
self._data_loader(uris) for uris in query_results["uris"]
]
# Remove URIs from the result if they weren't requested
if "uris" not in include:
query_results["uris"] = None
return query_results
def modify(
self, name: Optional[str] = None, metadata: Optional[CollectionMetadata] = None
) -> None:
"""Modify the collection name or metadata
Args:
name: The updated name for the collection. Optional.
metadata: The updated metadata for the collection. Optional.
Returns:
None
"""
if metadata is not None:
validate_metadata(metadata)
if "hnsw:space" in metadata:
raise ValueError(
"Changing the distance function of a collection once it is created is not supported currently.")
self._client._modify(id=self.id, new_name=name, new_metadata=metadata)
if name:
self.name = name
if metadata:
self.metadata = metadata
def update(
self,
ids: OneOrMany[ID],
embeddings: Optional[
Union[
OneOrMany[Embedding],
OneOrMany[np.ndarray],
]
] = None,
metadatas: Optional[OneOrMany[Metadata]] = None,
documents: Optional[OneOrMany[Document]] = None,
images: Optional[OneOrMany[Image]] = None,
uris: Optional[OneOrMany[URI]] = None,
) -> None:
"""Update the embeddings, metadatas or documents for provided ids.
Args:
ids: The ids of the embeddings to update
embeddings: The embeddings to update. If None, embeddings will be computed based on the documents or images using the embedding_function set for the Collection. Optional.
metadatas: The metadata to associate with the embeddings. When querying, you can filter on this metadata. Optional.
documents: The documents to associate with the embeddings. Optional.
images: The images to associate with the embeddings. Optional.
Returns:
None
"""
(
ids,
embeddings,
metadatas,
documents,
images,
uris,
) = self._validate_embedding_set(
ids,
embeddings,
metadatas,
documents,
images,
uris,
require_embeddings_or_data=False,
)
if embeddings is None:
if documents is not None:
embeddings = self._embed(input=documents)
elif images is not None:
embeddings = self._embed(input=images)
self._client._update(self.id, ids, embeddings, metadatas, documents, uris)
def upsert(
self,
ids: OneOrMany[ID],
embeddings: Optional[
Union[
OneOrMany[Embedding],
OneOrMany[np.ndarray],
]
] = None,
metadatas: Optional[OneOrMany[Metadata]] = None,
documents: Optional[OneOrMany[Document]] = None,
images: Optional[OneOrMany[Image]] = None,
uris: Optional[OneOrMany[URI]] = None,
) -> None:
"""Update the embeddings, metadatas or documents for provided ids, or create them if they don't exist.
Args:
ids: The ids of the embeddings to update
embeddings: The embeddings to add. If None, embeddings will be computed based on the documents using the embedding_function set for the Collection. Optional.
metadatas: The metadata to associate with the embeddings. When querying, you can filter on this metadata. Optional.
documents: The documents to associate with the embeddings. Optional.
Returns:
None
"""
(
ids,
embeddings,
metadatas,
documents,
images,
uris,
) = self._validate_embedding_set(
ids, embeddings, metadatas, documents, images, uris
)
if embeddings is None:
if documents is not None:
embeddings = self._embed(input=documents)
else:
embeddings = self._embed(input=images)
self._client._upsert(
collection_id=self.id,
ids=ids,
embeddings=embeddings,
metadatas=metadatas,
documents=documents,
uris=uris,
)
def delete(
self,
ids: Optional[IDs] = None,
where: Optional[Where] = None,
where_document: Optional[WhereDocument] = None,
) -> None:
"""Delete the embeddings based on ids and/or a where filter
Args:
ids: The ids of the embeddings to delete
where: A Where type dict used to filter the delection by. E.g. `{"$and": ["color" : "red", "price": {"$gte": 4.20}]}`. Optional.
where_document: A WhereDocument type dict used to filter the deletion by the document content. E.g. `{$contains: {"text": "hello"}}`. Optional.
Returns:
None
Raises:
ValueError: If you don't provide either ids, where, or where_document
"""
ids = validate_ids(maybe_cast_one_to_many_ids(ids)) if ids else None
where = validate_where(where) if where else None
where_document = (
validate_where_document(where_document) if where_document else None
)
self._client._delete(self.id, ids, where, where_document)
def _validate_embedding_set(
self,
ids: OneOrMany[ID],
embeddings: Optional[
Union[
OneOrMany[Embedding],
OneOrMany[np.ndarray],
]
],
metadatas: Optional[OneOrMany[Metadata]],
documents: Optional[OneOrMany[Document]],
images: Optional[OneOrMany[Image]] = None,
uris: Optional[OneOrMany[URI]] = None,
require_embeddings_or_data: bool = True,
) -> Tuple[
IDs,
Optional[Embeddings],
Optional[Metadatas],
Optional[Documents],
Optional[Images],
Optional[URIs],
]:
valid_ids = validate_ids(maybe_cast_one_to_many_ids(ids))
valid_embeddings = (
validate_embeddings(
self._normalize_embeddings(maybe_cast_one_to_many_embedding(embeddings))
)
if embeddings is not None
else None
)
valid_metadatas = (
validate_metadatas(maybe_cast_one_to_many_metadata(metadatas))
if metadatas is not None
else None
)
valid_documents = (
maybe_cast_one_to_many_document(documents)
if documents is not None
else None
)
valid_images = (
maybe_cast_one_to_many_image(images) if images is not None else None
)
valid_uris = maybe_cast_one_to_many_uri(uris) if uris is not None else None
# Check that one of embeddings or ducuments or images is provided
if require_embeddings_or_data:
if (
valid_embeddings is None
and valid_documents is None
and valid_images is None
and valid_uris is None
):
raise ValueError(
"You must provide embeddings, documents, images, or uris."
)
# Only one of documents or images can be provided
if valid_documents is not None and valid_images is not None:
raise ValueError("You can only provide documents or images, not both.")
# Check that, if they're provided, the lengths of the arrays match the length of ids
if valid_embeddings is not None and len(valid_embeddings) != len(valid_ids):
raise ValueError(
f"Number of embeddings {len(valid_embeddings)} must match number of ids {len(valid_ids)}"
)
if valid_metadatas is not None and len(valid_metadatas) != len(valid_ids):
raise ValueError(
f"Number of metadatas {len(valid_metadatas)} must match number of ids {len(valid_ids)}"
)
if valid_documents is not None and len(valid_documents) != len(valid_ids):
raise ValueError(
f"Number of documents {len(valid_documents)} must match number of ids {len(valid_ids)}"
)
if valid_images is not None and len(valid_images) != len(valid_ids):
raise ValueError(
f"Number of images {len(valid_images)} must match number of ids {len(valid_ids)}"
)
if valid_uris is not None and len(valid_uris) != len(valid_ids):
raise ValueError(
f"Number of uris {len(valid_uris)} must match number of ids {len(valid_ids)}"
)
return (
valid_ids,
valid_embeddings,
valid_metadatas,
valid_documents,
valid_images,
valid_uris,
)
@staticmethod
def _normalize_embeddings(
embeddings: Union[
OneOrMany[Embedding],
OneOrMany[np.ndarray],
]
) -> Embeddings:
if isinstance(embeddings, np.ndarray):
return embeddings.tolist()
return embeddings
def _embed(self, input: Any) -> Embeddings:
if self._embedding_function is None:
raise ValueError(
"You must provide an embedding function to compute embeddings."
"https://docs.trychroma.com/embeddings"
)
return self._embedding_function(input=input)
| (client: 'ServerAPI', name: str, id: uuid.UUID, embedding_function: Optional[chromadb.api.types.EmbeddingFunction[Union[List[str], List[numpy.ndarray[Any, numpy.dtype[Union[numpy.uint64, numpy.int64, numpy.float64]]]]]]] = <chromadb.utils.embedding_functions.ONNXMiniLM_L6_V2 object at 0x7fd508aead70>, data_loader: Optional[chromadb.api.types.DataLoader[List[Optional[numpy.ndarray[Any, numpy.dtype[Union[numpy.uint64, numpy.int64, numpy.float64]]]]]]] = None, tenant: Optional[str] = None, database: Optional[str] = None, metadata: Optional[Dict[str, Any]] = None) -> None |
730,440 | chromadb.api.models.Collection | __init__ | null | def __init__(
self,
client: "ServerAPI",
name: str,
id: UUID,
embedding_function: Optional[
EmbeddingFunction[Embeddable]
] = ef.DefaultEmbeddingFunction(), # type: ignore
data_loader: Optional[DataLoader[Loadable]] = None,
tenant: Optional[str] = None,
database: Optional[str] = None,
metadata: Optional[CollectionMetadata] = None,
):
super().__init__(
name=name, metadata=metadata, id=id, tenant=tenant, database=database
)
self._client = client
# Check to make sure the embedding function has the right signature, as defined by the EmbeddingFunction protocol
if embedding_function is not None:
validate_embedding_function(embedding_function)
self._embedding_function = embedding_function
self._data_loader = data_loader
| (self, client: 'ServerAPI', name: str, id: uuid.UUID, embedding_function: Optional[chromadb.api.types.EmbeddingFunction[Union[List[str], List[numpy.ndarray[Any, numpy.dtype[Union[numpy.uint64, numpy.int64, numpy.float64]]]]]]] = <chromadb.utils.embedding_functions.ONNXMiniLM_L6_V2 object at 0x7fd508aead70>, data_loader: Optional[chromadb.api.types.DataLoader[List[Optional[numpy.ndarray[Any, numpy.dtype[Union[numpy.uint64, numpy.int64, numpy.float64]]]]]]] = None, tenant: Optional[str] = None, database: Optional[str] = None, metadata: Optional[Dict[str, Any]] = None) |
730,454 | chromadb.api.models.Collection | _embed | null | def _embed(self, input: Any) -> Embeddings:
if self._embedding_function is None:
raise ValueError(
"You must provide an embedding function to compute embeddings."
"https://docs.trychroma.com/embeddings"
)
return self._embedding_function(input=input)
| (self, input: Any) -> List[Union[Sequence[float], Sequence[int]]] |
730,456 | chromadb.api.models.Collection | _normalize_embeddings | null | @staticmethod
def _normalize_embeddings(
embeddings: Union[
OneOrMany[Embedding],
OneOrMany[np.ndarray],
]
) -> Embeddings:
if isinstance(embeddings, np.ndarray):
return embeddings.tolist()
return embeddings
| (embeddings: Union[Sequence[float], Sequence[int], List[Union[Sequence[float], Sequence[int]]], numpy.ndarray, List[numpy.ndarray]]) -> List[Union[Sequence[float], Sequence[int]]] |
730,457 | chromadb.api.models.Collection | _validate_embedding_set | null | def _validate_embedding_set(
self,
ids: OneOrMany[ID],
embeddings: Optional[
Union[
OneOrMany[Embedding],
OneOrMany[np.ndarray],
]
],
metadatas: Optional[OneOrMany[Metadata]],
documents: Optional[OneOrMany[Document]],
images: Optional[OneOrMany[Image]] = None,
uris: Optional[OneOrMany[URI]] = None,
require_embeddings_or_data: bool = True,
) -> Tuple[
IDs,
Optional[Embeddings],
Optional[Metadatas],
Optional[Documents],
Optional[Images],
Optional[URIs],
]:
valid_ids = validate_ids(maybe_cast_one_to_many_ids(ids))
valid_embeddings = (
validate_embeddings(
self._normalize_embeddings(maybe_cast_one_to_many_embedding(embeddings))
)
if embeddings is not None
else None
)
valid_metadatas = (
validate_metadatas(maybe_cast_one_to_many_metadata(metadatas))
if metadatas is not None
else None
)
valid_documents = (
maybe_cast_one_to_many_document(documents)
if documents is not None
else None
)
valid_images = (
maybe_cast_one_to_many_image(images) if images is not None else None
)
valid_uris = maybe_cast_one_to_many_uri(uris) if uris is not None else None
# Check that one of embeddings or ducuments or images is provided
if require_embeddings_or_data:
if (
valid_embeddings is None
and valid_documents is None
and valid_images is None
and valid_uris is None
):
raise ValueError(
"You must provide embeddings, documents, images, or uris."
)
# Only one of documents or images can be provided
if valid_documents is not None and valid_images is not None:
raise ValueError("You can only provide documents or images, not both.")
# Check that, if they're provided, the lengths of the arrays match the length of ids
if valid_embeddings is not None and len(valid_embeddings) != len(valid_ids):
raise ValueError(
f"Number of embeddings {len(valid_embeddings)} must match number of ids {len(valid_ids)}"
)
if valid_metadatas is not None and len(valid_metadatas) != len(valid_ids):
raise ValueError(
f"Number of metadatas {len(valid_metadatas)} must match number of ids {len(valid_ids)}"
)
if valid_documents is not None and len(valid_documents) != len(valid_ids):
raise ValueError(
f"Number of documents {len(valid_documents)} must match number of ids {len(valid_ids)}"
)
if valid_images is not None and len(valid_images) != len(valid_ids):
raise ValueError(
f"Number of images {len(valid_images)} must match number of ids {len(valid_ids)}"
)
if valid_uris is not None and len(valid_uris) != len(valid_ids):
raise ValueError(
f"Number of uris {len(valid_uris)} must match number of ids {len(valid_ids)}"
)
return (
valid_ids,
valid_embeddings,
valid_metadatas,
valid_documents,
valid_images,
valid_uris,
)
| (self, ids: Union[str, List[str]], embeddings: Union[Sequence[float], Sequence[int], List[Union[Sequence[float], Sequence[int]]], numpy.ndarray, List[numpy.ndarray], NoneType], metadatas: Union[Mapping[str, Union[str, int, float, bool]], List[Mapping[str, Union[str, int, float, bool]]], NoneType], documents: Union[str, List[str], NoneType], images: Union[numpy.ndarray[Any, numpy.dtype[Union[numpy.uint64, numpy.int64, numpy.float64]]], List[numpy.ndarray[Any, numpy.dtype[Union[numpy.uint64, numpy.int64, numpy.float64]]]], NoneType] = None, uris: Union[str, List[str], NoneType] = None, require_embeddings_or_data: bool = True) -> Tuple[List[str], Optional[List[Union[Sequence[float], Sequence[int]]]], Optional[List[Mapping[str, Union[str, int, float, bool]]]], Optional[List[str]], Optional[List[numpy.ndarray[Any, numpy.dtype[Union[numpy.uint64, numpy.int64, numpy.float64]]]]], Optional[List[str]]] |
730,458 | chromadb.api.models.Collection | add | Add embeddings to the data store.
Args:
ids: The ids of the embeddings you wish to add
embeddings: The embeddings to add. If None, embeddings will be computed based on the documents or images using the embedding_function set for the Collection. Optional.
metadatas: The metadata to associate with the embeddings. When querying, you can filter on this metadata. Optional.
documents: The documents to associate with the embeddings. Optional.
images: The images to associate with the embeddings. Optional.
uris: The uris of the images to associate with the embeddings. Optional.
Returns:
None
Raises:
ValueError: If you don't provide either embeddings or documents
ValueError: If the length of ids, embeddings, metadatas, or documents don't match
ValueError: If you don't provide an embedding function and don't provide embeddings
ValueError: If you provide both embeddings and documents
ValueError: If you provide an id that already exists
| def add(
self,
ids: OneOrMany[ID],
embeddings: Optional[
Union[
OneOrMany[Embedding],
OneOrMany[np.ndarray],
]
] = None,
metadatas: Optional[OneOrMany[Metadata]] = None,
documents: Optional[OneOrMany[Document]] = None,
images: Optional[OneOrMany[Image]] = None,
uris: Optional[OneOrMany[URI]] = None,
) -> None:
"""Add embeddings to the data store.
Args:
ids: The ids of the embeddings you wish to add
embeddings: The embeddings to add. If None, embeddings will be computed based on the documents or images using the embedding_function set for the Collection. Optional.
metadatas: The metadata to associate with the embeddings. When querying, you can filter on this metadata. Optional.
documents: The documents to associate with the embeddings. Optional.
images: The images to associate with the embeddings. Optional.
uris: The uris of the images to associate with the embeddings. Optional.
Returns:
None
Raises:
ValueError: If you don't provide either embeddings or documents
ValueError: If the length of ids, embeddings, metadatas, or documents don't match
ValueError: If you don't provide an embedding function and don't provide embeddings
ValueError: If you provide both embeddings and documents
ValueError: If you provide an id that already exists
"""
(
ids,
embeddings,
metadatas,
documents,
images,
uris,
) = self._validate_embedding_set(
ids, embeddings, metadatas, documents, images, uris
)
# We need to compute the embeddings if they're not provided
if embeddings is None:
# At this point, we know that one of documents or images are provided from the validation above
if documents is not None:
embeddings = self._embed(input=documents)
elif images is not None:
embeddings = self._embed(input=images)
else:
if uris is None:
raise ValueError(
"You must provide either embeddings, documents, images, or uris."
)
if self._data_loader is None:
raise ValueError(
"You must set a data loader on the collection if loading from URIs."
)
embeddings = self._embed(self._data_loader(uris))
self._client._add(ids, self.id, embeddings, metadatas, documents, uris)
| (self, ids: Union[str, List[str]], embeddings: Union[Sequence[float], Sequence[int], List[Union[Sequence[float], Sequence[int]]], numpy.ndarray, List[numpy.ndarray], NoneType] = None, metadatas: Union[Mapping[str, Union[str, int, float, bool]], List[Mapping[str, Union[str, int, float, bool]]], NoneType] = None, documents: Union[str, List[str], NoneType] = None, images: Union[numpy.ndarray[Any, numpy.dtype[Union[numpy.uint64, numpy.int64, numpy.float64]]], List[numpy.ndarray[Any, numpy.dtype[Union[numpy.uint64, numpy.int64, numpy.float64]]]], NoneType] = None, uris: Union[str, List[str], NoneType] = None) -> NoneType |
730,460 | chromadb.api.models.Collection | count | The total number of embeddings added to the database
Returns:
int: The total number of embeddings added to the database
| def count(self) -> int:
"""The total number of embeddings added to the database
Returns:
int: The total number of embeddings added to the database
"""
return self._client._count(collection_id=self.id)
| (self) -> int |
730,461 | chromadb.api.models.Collection | delete | Delete the embeddings based on ids and/or a where filter
Args:
ids: The ids of the embeddings to delete
where: A Where type dict used to filter the delection by. E.g. `{"$and": ["color" : "red", "price": {"$gte": 4.20}]}`. Optional.
where_document: A WhereDocument type dict used to filter the deletion by the document content. E.g. `{$contains: {"text": "hello"}}`. Optional.
Returns:
None
Raises:
ValueError: If you don't provide either ids, where, or where_document
| def delete(
self,
ids: Optional[IDs] = None,
where: Optional[Where] = None,
where_document: Optional[WhereDocument] = None,
) -> None:
"""Delete the embeddings based on ids and/or a where filter
Args:
ids: The ids of the embeddings to delete
where: A Where type dict used to filter the delection by. E.g. `{"$and": ["color" : "red", "price": {"$gte": 4.20}]}`. Optional.
where_document: A WhereDocument type dict used to filter the deletion by the document content. E.g. `{$contains: {"text": "hello"}}`. Optional.
Returns:
None
Raises:
ValueError: If you don't provide either ids, where, or where_document
"""
ids = validate_ids(maybe_cast_one_to_many_ids(ids)) if ids else None
where = validate_where(where) if where else None
where_document = (
validate_where_document(where_document) if where_document else None
)
self._client._delete(self.id, ids, where, where_document)
| (self, ids: Optional[List[str]] = None, where: Optional[Dict[Union[str, Literal['$and'], Literal['$or']], Union[str, int, float, bool, Dict[Union[Literal['$gt'], Literal['$gte'], Literal['$lt'], Literal['$lte'], Literal['$ne'], Literal['$eq'], Literal['$and'], Literal['$or']], Union[str, int, float, bool]], Dict[Union[Literal['$in'], Literal['$nin']], List[Union[str, int, float, bool]]], List[Dict[Union[str, Literal['$and'], Literal['$or']], Union[str, int, float, bool, Dict[Union[Literal['$gt'], Literal['$gte'], Literal['$lt'], Literal['$lte'], Literal['$ne'], Literal['$eq'], Literal['$and'], Literal['$or']], Union[str, int, float, bool]], Dict[Union[Literal['$in'], Literal['$nin']], List[Union[str, int, float, bool]]], List[ForwardRef('Where')]]]]]]] = None, where_document: Optional[Dict[Union[Literal['$contains'], Literal['$not_contains'], Literal['$and'], Literal['$or']], Union[str, List[Dict[Union[Literal['$contains'], Literal['$not_contains'], Literal['$and'], Literal['$or']], Union[str, List[ForwardRef('WhereDocument')]]]]]]] = None) -> NoneType |
730,463 | chromadb.api.models.Collection | get | Get embeddings and their associate data from the data store. If no ids or where filter is provided returns
all embeddings up to limit starting at offset.
Args:
ids: The ids of the embeddings to get. Optional.
where: A Where type dict used to filter results by. E.g. `{"$and": ["color" : "red", "price": {"$gte": 4.20}]}`. Optional.
limit: The number of documents to return. Optional.
offset: The offset to start returning results from. Useful for paging results with limit. Optional.
where_document: A WhereDocument type dict used to filter by the documents. E.g. `{$contains: {"text": "hello"}}`. Optional.
include: A list of what to include in the results. Can contain `"embeddings"`, `"metadatas"`, `"documents"`. Ids are always included. Defaults to `["metadatas", "documents"]`. Optional.
Returns:
GetResult: A GetResult object containing the results.
| def get(
self,
ids: Optional[OneOrMany[ID]] = None,
where: Optional[Where] = None,
limit: Optional[int] = None,
offset: Optional[int] = None,
where_document: Optional[WhereDocument] = None,
include: Include = ["metadatas", "documents"],
) -> GetResult:
"""Get embeddings and their associate data from the data store. If no ids or where filter is provided returns
all embeddings up to limit starting at offset.
Args:
ids: The ids of the embeddings to get. Optional.
where: A Where type dict used to filter results by. E.g. `{"$and": ["color" : "red", "price": {"$gte": 4.20}]}`. Optional.
limit: The number of documents to return. Optional.
offset: The offset to start returning results from. Useful for paging results with limit. Optional.
where_document: A WhereDocument type dict used to filter by the documents. E.g. `{$contains: {"text": "hello"}}`. Optional.
include: A list of what to include in the results. Can contain `"embeddings"`, `"metadatas"`, `"documents"`. Ids are always included. Defaults to `["metadatas", "documents"]`. Optional.
Returns:
GetResult: A GetResult object containing the results.
"""
valid_where = validate_where(where) if where else None
valid_where_document = (
validate_where_document(where_document) if where_document else None
)
valid_ids = validate_ids(maybe_cast_one_to_many_ids(ids)) if ids else None
valid_include = validate_include(include, allow_distances=False)
if "data" in include and self._data_loader is None:
raise ValueError(
"You must set a data loader on the collection if loading from URIs."
)
# We need to include uris in the result from the API to load datas
if "data" in include and "uris" not in include:
valid_include.append("uris")
get_results = self._client._get(
self.id,
valid_ids,
valid_where,
None,
limit,
offset,
where_document=valid_where_document,
include=valid_include,
)
if (
"data" in include
and self._data_loader is not None
and get_results["uris"] is not None
):
get_results["data"] = self._data_loader(get_results["uris"])
# Remove URIs from the result if they weren't requested
if "uris" not in include:
get_results["uris"] = None
return get_results
| (self, ids: Union[str, List[str], NoneType] = None, where: Optional[Dict[Union[str, Literal['$and'], Literal['$or']], Union[str, int, float, bool, Dict[Union[Literal['$gt'], Literal['$gte'], Literal['$lt'], Literal['$lte'], Literal['$ne'], Literal['$eq'], Literal['$and'], Literal['$or']], Union[str, int, float, bool]], Dict[Union[Literal['$in'], Literal['$nin']], List[Union[str, int, float, bool]]], List[Dict[Union[str, Literal['$and'], Literal['$or']], Union[str, int, float, bool, Dict[Union[Literal['$gt'], Literal['$gte'], Literal['$lt'], Literal['$lte'], Literal['$ne'], Literal['$eq'], Literal['$and'], Literal['$or']], Union[str, int, float, bool]], Dict[Union[Literal['$in'], Literal['$nin']], List[Union[str, int, float, bool]]], List[ForwardRef('Where')]]]]]]] = None, limit: Optional[int] = None, offset: Optional[int] = None, where_document: Optional[Dict[Union[Literal['$contains'], Literal['$not_contains'], Literal['$and'], Literal['$or']], Union[str, List[Dict[Union[Literal['$contains'], Literal['$not_contains'], Literal['$and'], Literal['$or']], Union[str, List[ForwardRef('WhereDocument')]]]]]]] = None, include: List[Union[Literal['documents'], Literal['embeddings'], Literal['metadatas'], Literal['distances'], Literal['uris'], Literal['data']]] = ['metadatas', 'documents']) -> chromadb.api.types.GetResult |
730,469 | chromadb.api.models.Collection | modify | Modify the collection name or metadata
Args:
name: The updated name for the collection. Optional.
metadata: The updated metadata for the collection. Optional.
Returns:
None
| def modify(
self, name: Optional[str] = None, metadata: Optional[CollectionMetadata] = None
) -> None:
"""Modify the collection name or metadata
Args:
name: The updated name for the collection. Optional.
metadata: The updated metadata for the collection. Optional.
Returns:
None
"""
if metadata is not None:
validate_metadata(metadata)
if "hnsw:space" in metadata:
raise ValueError(
"Changing the distance function of a collection once it is created is not supported currently.")
self._client._modify(id=self.id, new_name=name, new_metadata=metadata)
if name:
self.name = name
if metadata:
self.metadata = metadata
| (self, name: Optional[str] = None, metadata: Optional[Dict[str, Any]] = None) -> NoneType |
730,470 | chromadb.api.models.Collection | peek | Get the first few results in the database up to limit
Args:
limit: The number of results to return.
Returns:
GetResult: A GetResult object containing the results.
| def peek(self, limit: int = 10) -> GetResult:
"""Get the first few results in the database up to limit
Args:
limit: The number of results to return.
Returns:
GetResult: A GetResult object containing the results.
"""
return self._client._peek(self.id, limit)
| (self, limit: int = 10) -> chromadb.api.types.GetResult |
730,471 | chromadb.api.models.Collection | query | Get the n_results nearest neighbor embeddings for provided query_embeddings or query_texts.
Args:
query_embeddings: The embeddings to get the closes neighbors of. Optional.
query_texts: The document texts to get the closes neighbors of. Optional.
query_images: The images to get the closes neighbors of. Optional.
n_results: The number of neighbors to return for each query_embedding or query_texts. Optional.
where: A Where type dict used to filter results by. E.g. `{"$and": ["color" : "red", "price": {"$gte": 4.20}]}`. Optional.
where_document: A WhereDocument type dict used to filter by the documents. E.g. `{$contains: {"text": "hello"}}`. Optional.
include: A list of what to include in the results. Can contain `"embeddings"`, `"metadatas"`, `"documents"`, `"distances"`. Ids are always included. Defaults to `["metadatas", "documents", "distances"]`. Optional.
Returns:
QueryResult: A QueryResult object containing the results.
Raises:
ValueError: If you don't provide either query_embeddings, query_texts, or query_images
ValueError: If you provide both query_embeddings and query_texts
ValueError: If you provide both query_embeddings and query_images
ValueError: If you provide both query_texts and query_images
| def query(
self,
query_embeddings: Optional[
Union[
OneOrMany[Embedding],
OneOrMany[np.ndarray],
]
] = None,
query_texts: Optional[OneOrMany[Document]] = None,
query_images: Optional[OneOrMany[Image]] = None,
query_uris: Optional[OneOrMany[URI]] = None,
n_results: int = 10,
where: Optional[Where] = None,
where_document: Optional[WhereDocument] = None,
include: Include = ["metadatas", "documents", "distances"],
) -> QueryResult:
"""Get the n_results nearest neighbor embeddings for provided query_embeddings or query_texts.
Args:
query_embeddings: The embeddings to get the closes neighbors of. Optional.
query_texts: The document texts to get the closes neighbors of. Optional.
query_images: The images to get the closes neighbors of. Optional.
n_results: The number of neighbors to return for each query_embedding or query_texts. Optional.
where: A Where type dict used to filter results by. E.g. `{"$and": ["color" : "red", "price": {"$gte": 4.20}]}`. Optional.
where_document: A WhereDocument type dict used to filter by the documents. E.g. `{$contains: {"text": "hello"}}`. Optional.
include: A list of what to include in the results. Can contain `"embeddings"`, `"metadatas"`, `"documents"`, `"distances"`. Ids are always included. Defaults to `["metadatas", "documents", "distances"]`. Optional.
Returns:
QueryResult: A QueryResult object containing the results.
Raises:
ValueError: If you don't provide either query_embeddings, query_texts, or query_images
ValueError: If you provide both query_embeddings and query_texts
ValueError: If you provide both query_embeddings and query_images
ValueError: If you provide both query_texts and query_images
"""
# Users must provide only one of query_embeddings, query_texts, query_images, or query_uris
if not (
(query_embeddings is not None)
^ (query_texts is not None)
^ (query_images is not None)
^ (query_uris is not None)
):
raise ValueError(
"You must provide one of query_embeddings, query_texts, query_images, or query_uris."
)
valid_where = validate_where(where) if where else {}
valid_where_document = (
validate_where_document(where_document) if where_document else {}
)
valid_query_embeddings = (
validate_embeddings(
self._normalize_embeddings(
maybe_cast_one_to_many_embedding(query_embeddings)
)
)
if query_embeddings is not None
else None
)
valid_query_texts = (
maybe_cast_one_to_many_document(query_texts)
if query_texts is not None
else None
)
valid_query_images = (
maybe_cast_one_to_many_image(query_images)
if query_images is not None
else None
)
valid_query_uris = (
maybe_cast_one_to_many_uri(query_uris) if query_uris is not None else None
)
valid_include = validate_include(include, allow_distances=True)
valid_n_results = validate_n_results(n_results)
# If query_embeddings are not provided, we need to compute them from the inputs
if valid_query_embeddings is None:
if query_texts is not None:
valid_query_embeddings = self._embed(input=valid_query_texts)
elif query_images is not None:
valid_query_embeddings = self._embed(input=valid_query_images)
else:
if valid_query_uris is None:
raise ValueError(
"You must provide either query_embeddings, query_texts, query_images, or query_uris."
)
if self._data_loader is None:
raise ValueError(
"You must set a data loader on the collection if loading from URIs."
)
valid_query_embeddings = self._embed(
self._data_loader(valid_query_uris)
)
if "data" in include and "uris" not in include:
valid_include.append("uris")
query_results = self._client._query(
collection_id=self.id,
query_embeddings=valid_query_embeddings,
n_results=valid_n_results,
where=valid_where,
where_document=valid_where_document,
include=include,
)
if (
"data" in include
and self._data_loader is not None
and query_results["uris"] is not None
):
query_results["data"] = [
self._data_loader(uris) for uris in query_results["uris"]
]
# Remove URIs from the result if they weren't requested
if "uris" not in include:
query_results["uris"] = None
return query_results
| (self, query_embeddings: Union[Sequence[float], Sequence[int], List[Union[Sequence[float], Sequence[int]]], numpy.ndarray, List[numpy.ndarray], NoneType] = None, query_texts: Union[str, List[str], NoneType] = None, query_images: Union[numpy.ndarray[Any, numpy.dtype[Union[numpy.uint64, numpy.int64, numpy.float64]]], List[numpy.ndarray[Any, numpy.dtype[Union[numpy.uint64, numpy.int64, numpy.float64]]]], NoneType] = None, query_uris: Union[str, List[str], NoneType] = None, n_results: int = 10, where: Optional[Dict[Union[str, Literal['$and'], Literal['$or']], Union[str, int, float, bool, Dict[Union[Literal['$gt'], Literal['$gte'], Literal['$lt'], Literal['$lte'], Literal['$ne'], Literal['$eq'], Literal['$and'], Literal['$or']], Union[str, int, float, bool]], Dict[Union[Literal['$in'], Literal['$nin']], List[Union[str, int, float, bool]]], List[Dict[Union[str, Literal['$and'], Literal['$or']], Union[str, int, float, bool, Dict[Union[Literal['$gt'], Literal['$gte'], Literal['$lt'], Literal['$lte'], Literal['$ne'], Literal['$eq'], Literal['$and'], Literal['$or']], Union[str, int, float, bool]], Dict[Union[Literal['$in'], Literal['$nin']], List[Union[str, int, float, bool]]], List[ForwardRef('Where')]]]]]]] = None, where_document: Optional[Dict[Union[Literal['$contains'], Literal['$not_contains'], Literal['$and'], Literal['$or']], Union[str, List[Dict[Union[Literal['$contains'], Literal['$not_contains'], Literal['$and'], Literal['$or']], Union[str, List[ForwardRef('WhereDocument')]]]]]]] = None, include: List[Union[Literal['documents'], Literal['embeddings'], Literal['metadatas'], Literal['distances'], Literal['uris'], Literal['data']]] = ['metadatas', 'documents', 'distances']) -> chromadb.api.types.QueryResult |
730,472 | chromadb.api.models.Collection | update | Update the embeddings, metadatas or documents for provided ids.
Args:
ids: The ids of the embeddings to update
embeddings: The embeddings to update. If None, embeddings will be computed based on the documents or images using the embedding_function set for the Collection. Optional.
metadatas: The metadata to associate with the embeddings. When querying, you can filter on this metadata. Optional.
documents: The documents to associate with the embeddings. Optional.
images: The images to associate with the embeddings. Optional.
Returns:
None
| def update(
self,
ids: OneOrMany[ID],
embeddings: Optional[
Union[
OneOrMany[Embedding],
OneOrMany[np.ndarray],
]
] = None,
metadatas: Optional[OneOrMany[Metadata]] = None,
documents: Optional[OneOrMany[Document]] = None,
images: Optional[OneOrMany[Image]] = None,
uris: Optional[OneOrMany[URI]] = None,
) -> None:
"""Update the embeddings, metadatas or documents for provided ids.
Args:
ids: The ids of the embeddings to update
embeddings: The embeddings to update. If None, embeddings will be computed based on the documents or images using the embedding_function set for the Collection. Optional.
metadatas: The metadata to associate with the embeddings. When querying, you can filter on this metadata. Optional.
documents: The documents to associate with the embeddings. Optional.
images: The images to associate with the embeddings. Optional.
Returns:
None
"""
(
ids,
embeddings,
metadatas,
documents,
images,
uris,
) = self._validate_embedding_set(
ids,
embeddings,
metadatas,
documents,
images,
uris,
require_embeddings_or_data=False,
)
if embeddings is None:
if documents is not None:
embeddings = self._embed(input=documents)
elif images is not None:
embeddings = self._embed(input=images)
self._client._update(self.id, ids, embeddings, metadatas, documents, uris)
| (self, ids: Union[str, List[str]], embeddings: Union[Sequence[float], Sequence[int], List[Union[Sequence[float], Sequence[int]]], numpy.ndarray, List[numpy.ndarray], NoneType] = None, metadatas: Union[Mapping[str, Union[str, int, float, bool]], List[Mapping[str, Union[str, int, float, bool]]], NoneType] = None, documents: Union[str, List[str], NoneType] = None, images: Union[numpy.ndarray[Any, numpy.dtype[Union[numpy.uint64, numpy.int64, numpy.float64]]], List[numpy.ndarray[Any, numpy.dtype[Union[numpy.uint64, numpy.int64, numpy.float64]]]], NoneType] = None, uris: Union[str, List[str], NoneType] = None) -> NoneType |
730,473 | chromadb.api.models.Collection | upsert | Update the embeddings, metadatas or documents for provided ids, or create them if they don't exist.
Args:
ids: The ids of the embeddings to update
embeddings: The embeddings to add. If None, embeddings will be computed based on the documents using the embedding_function set for the Collection. Optional.
metadatas: The metadata to associate with the embeddings. When querying, you can filter on this metadata. Optional.
documents: The documents to associate with the embeddings. Optional.
Returns:
None
| def upsert(
self,
ids: OneOrMany[ID],
embeddings: Optional[
Union[
OneOrMany[Embedding],
OneOrMany[np.ndarray],
]
] = None,
metadatas: Optional[OneOrMany[Metadata]] = None,
documents: Optional[OneOrMany[Document]] = None,
images: Optional[OneOrMany[Image]] = None,
uris: Optional[OneOrMany[URI]] = None,
) -> None:
"""Update the embeddings, metadatas or documents for provided ids, or create them if they don't exist.
Args:
ids: The ids of the embeddings to update
embeddings: The embeddings to add. If None, embeddings will be computed based on the documents using the embedding_function set for the Collection. Optional.
metadatas: The metadata to associate with the embeddings. When querying, you can filter on this metadata. Optional.
documents: The documents to associate with the embeddings. Optional.
Returns:
None
"""
(
ids,
embeddings,
metadatas,
documents,
images,
uris,
) = self._validate_embedding_set(
ids, embeddings, metadatas, documents, images, uris
)
if embeddings is None:
if documents is not None:
embeddings = self._embed(input=documents)
else:
embeddings = self._embed(input=images)
self._client._upsert(
collection_id=self.id,
ids=ids,
embeddings=embeddings,
metadatas=metadatas,
documents=documents,
uris=uris,
)
| (self, ids: Union[str, List[str]], embeddings: Union[Sequence[float], Sequence[int], List[Union[Sequence[float], Sequence[int]]], numpy.ndarray, List[numpy.ndarray], NoneType] = None, metadatas: Union[Mapping[str, Union[str, int, float, bool]], List[Mapping[str, Union[str, int, float, bool]]], NoneType] = None, documents: Union[str, List[str], NoneType] = None, images: Union[numpy.ndarray[Any, numpy.dtype[Union[numpy.uint64, numpy.int64, numpy.float64]]], List[numpy.ndarray[Any, numpy.dtype[Union[numpy.uint64, numpy.int64, numpy.float64]]]], NoneType] = None, uris: Union[str, List[str], NoneType] = None) -> NoneType |
730,474 | chromadb.api.types | EmbeddingFunction | null | class EmbeddingFunction(Protocol[D]):
def __call__(self, input: D) -> Embeddings:
...
def __init_subclass__(cls) -> None:
super().__init_subclass__()
# Raise an exception if __call__ is not defined since it is expected to be defined
call = getattr(cls, "__call__")
def __call__(self: EmbeddingFunction[D], input: D) -> Embeddings:
result = call(self, input)
return validate_embeddings(maybe_cast_one_to_many_embedding(result))
setattr(cls, "__call__", __call__)
def embed_with_retries(self, input: D, **retry_kwargs: Dict) -> Embeddings:
return retry(**retry_kwargs)(self.__call__)(input)
| (*args, **kwargs) |
Subsets and Splits