Coverage for app / services / embedding_cache.py: 100%

60 statements  

« prev     ^ index     » next       coverage.py v7.13.4, created at 2026-10-31 11:23 +0000

1"""One embedding of each text a run embeds. 

2 

3A turn's searches embedded the same query again and again: once per 

4knowledge base searched, per lane (every lane's queries start with the 

5request), per corrective pass and per ``search_knowledge`` call. One plain 

6question about waterfall against the V-model made 16 embedding calls for 

7three distinct texts (scenario run, 27 October 2026). 

8 

9A run carries one :class:`EmbeddingCache` in its config 

10(``configurable[CONFIG_KEY]``, set by ``AgentGraphBuilder.run_config``, as 

11the source registry is), and ``Embedder.embed_many`` reads it with 

12:func:`current`: a text the run has embedded is not embedded again, and one 

13another branch is embedding now is waited for, not embedded twice — lanes 

14run side by side. Keyed by the embedder (``Embedder.key``) and the text as 

15it is embedded. Outside a run (indexing, a direct search) there is no cache, 

16and nothing changes. 

17""" 

18 

19from __future__ import annotations 

20 

21import asyncio 

22from collections.abc import Awaitable, Callable 

23from typing import Any 

24 

25#: Where a run's cache lives in its config's ``configurable``. ``__`` so 

26#: LangGraph never copies it into checkpoint metadata. 

27CONFIG_KEY = "__chainr_embeddings" 

28 

29Vector = list[float] 

30 

31 

32def _consume(future: asyncio.Future) -> None: 

33 """A failure no other branch waited for is still read, so asyncio never 

34 reports it as unretrieved.""" 

35 if not future.cancelled(): 

36 future.exception() 

37 

38 

39class EmbeddingCache: 

40 """A run's vectors, by (embedder, text), and those being made.""" 

41 

42 #: The most texts kept: a run embeds a handful of queries, and memory 

43 #: writes a few longer texts. Past it nothing more is kept, and texts 

44 #: are embedded as before. 

45 MAX_ENTRIES = 512 

46 

47 def __init__(self) -> None: 

48 self._done: dict[tuple[str, str], Vector] = {} 

49 self._pending: dict[tuple[str, str], asyncio.Future] = {} 

50 #: Texts served without an embedding call: what the cache saved. 

51 self.reused = 0 

52 

53 async def vectors( 

54 self, 

55 key: str, 

56 texts: list[str], 

57 embed: Callable[[list[str]], Awaitable[list[Vector]]], 

58 ) -> list[Vector]: 

59 """One vector per text of ``texts``, in order: kept ones, ones another 

60 branch is making, and the rest made by ``embed`` in one call.""" 

61 loop = asyncio.get_running_loop() 

62 found: dict[str, Vector] = {} 

63 waits: dict[str, asyncio.Future] = {} 

64 mine: dict[str, asyncio.Future] = {} 

65 for text in dict.fromkeys(texts): 

66 entry = (key, text) 

67 pending = self._pending.get(entry) 

68 if entry in self._done: 

69 found[text] = self._done[entry] 

70 self.reused += 1 

71 elif pending is not None and pending.get_loop() is loop: 

72 waits[text] = pending 

73 self.reused += 1 

74 else: 

75 future = loop.create_future() 

76 future.add_done_callback(_consume) 

77 self._pending[entry] = future 

78 mine[text] = future 

79 if mine: 

80 try: 

81 made = await embed(list(mine)) 

82 except BaseException as exc: 

83 for text, future in mine.items(): 

84 self._pending.pop((key, text), None) 

85 if not future.done(): 

86 future.set_exception(exc) 

87 raise 

88 for (text, future), vector in zip(mine.items(), made): 

89 self._pending.pop((key, text), None) 

90 if len(self._done) < self.MAX_ENTRIES: 

91 self._done[(key, text)] = vector 

92 found[text] = vector 

93 if not future.done(): 

94 future.set_result(vector) 

95 for text, future in waits.items(): 

96 found[text] = await future 

97 return [found[text] for text in texts] 

98 

99 

100def of_config(config: Any) -> EmbeddingCache | None: 

101 """The cache a run config carries, or None.""" 

102 if not isinstance(config, dict): 

103 return None 

104 found = (config.get("configurable") or {}).get(CONFIG_KEY) 

105 return found if isinstance(found, EmbeddingCache) else None 

106 

107 

108def current() -> EmbeddingCache | None: 

109 """The cache of the run this code is part of, or None outside a run.""" 

110 from langchain_core.runnables.config import var_child_runnable_config 

111 

112 return of_config(var_child_runnable_config.get())