import json from ._api import api_settings, embed from ._graph import identifier from ._state import cached_vectors, fingerprint from ._vectors import validate_vectors from .config import TARGETS def embed_graph(graph, targets, cache, prop, batch_size, limit): settings = api_settings() source = fingerprint(settings) counts = {} for name in targets: target = TARGETS[name] if prop in {target.key, target.text, target.property}: raise ValueError('API embeddings require a separate property, for example api_embedding.') graph.check_source(target, prop, source) dimension = settings['dimensions'] or None existing = graph.run(f'MATCH (n:{target.label}) WHERE n.{identifier(prop)} IS NOT NULL RETURN DISTINCT size(n.{identifier(prop)}) AS dim') if existing: if len(existing) != 1 or (dimension and existing[0]['dim'] != dimension): raise ValueError('Existing vector dimensions are inconsistent with configuration.') dimension = existing[0]['dim'] written = 0 while not limit or written < limit: size = min(batch_size, limit - written) if limit else batch_size rows = graph.run(f'MATCH (n:{target.label}) WHERE n.{identifier(prop)} IS NULL AND n.{target.text} IS NOT NULL AND trim(n.{target.text}) <> "" RETURN n.{target.key} AS key,n.{target.text} AS text ORDER BY key LIMIT $size', size=size) if not rows: break key = fingerprint({'source': source, 'target': name, 'rows': rows}) vectors = cached_vectors(cache, key, lambda: embed(settings, [row['text'] for row in rows])) vectors = validate_vectors(vectors, dimension) dimension = len(vectors[0]) graph.write(target, prop, source, [{'key': row['key'], 'vector': vector} for row, vector in zip(rows, vectors)]) written += len(rows) print(json.dumps({'target': name, 'vectors_added': written, 'dimension': dimension}), flush=True) counts[name] = written return counts