Skip to content

Commit 6ed8e7d

Browse files
authored
Fix issue of last cached element in batch not having IO data (#191)
* Fix issue of last cached element in batch not having IO data. * Minor formatting change.
1 parent f07b6f2 commit 6ed8e7d

2 files changed

Lines changed: 34 additions & 2 deletions

File tree

spacy_llm/pipeline/llm.py

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -218,8 +218,6 @@ def _process_docs(self, docs: List[Doc]) -> List[Doc]:
218218
final_docs.append(cached_doc)
219219
else:
220220
doc = next(modified_docs)
221-
self._cache.add(doc)
222-
final_docs.append(doc)
223221

224222
if self._save_io:
225223
# Make sure the `llm_io` field is set
@@ -230,6 +228,9 @@ def _process_docs(self, docs: List[Doc]) -> List[Doc]:
230228
llm_io["prompt"] = str(next(prompts_iters[2]))
231229
llm_io["response"] = str(next(responses_iters[2]))
232230

231+
self._cache.add(doc)
232+
final_docs.append(doc)
233+
233234
return final_docs
234235

235236
def to_bytes(

spacy_llm/tests/test_cache.py

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import copy
2+
import os
23
import time
34
from pathlib import Path
45
from typing import Dict
@@ -10,6 +11,7 @@
1011
from spacy.tokens import DocBin
1112

1213
from ..cache import BatchCache
14+
from .compat import has_openai_key
1315

1416
_DEFAULT_CFG = {
1517
"backend": {"api": "NoOp", "config": {"model": "NoOp"}},
@@ -153,3 +155,32 @@ def test_path_dir_created():
153155
config["cache"]["path"] = str(tmpdir / "new_dir")
154156
spacy.blank("en").add_pipe("llm", config=config)
155157
assert (tmpdir / "new_dir").exists()
158+
159+
160+
@pytest.mark.external
161+
@pytest.mark.skipif(has_openai_key is False, reason="OpenAI API key not available")
162+
def test_caching_llm_io() -> None:
163+
"""Test availability of LLM IO after caching."""
164+
with spacy.util.make_tempdir() as tmpdir:
165+
config = copy.deepcopy(_DEFAULT_CFG)
166+
config["backend"]["api"] = "OpenAI" # type: ignore[index]
167+
config["backend"]["config"] = {"model": "gpt-3.5-turbo"} # type: ignore[index]
168+
config["cache"]["path"] = str(tmpdir) # type: ignore[index]
169+
config["cache"]["batch_size"] = 3 # type: ignore[index]
170+
config["save_io"] = True
171+
nlp = spacy.blank("en")
172+
nlp.add_pipe("llm", config=config)
173+
docs = [nlp(txt) for txt in ("What's 1+1?", "What's 2+2?", "What's 3+3?")]
174+
175+
assert all([doc.user_data["llm_io"]["llm"]] for doc in docs)
176+
cached_file_names = [
177+
f
178+
for f in os.listdir(tmpdir)
179+
if os.path.isfile(tmpdir / f) and f.endswith(".spacy")
180+
]
181+
assert len(cached_file_names) == 1
182+
cached_docs = list(
183+
DocBin().from_disk(tmpdir / cached_file_names[0]).get_docs(nlp.vocab)
184+
)
185+
assert len(cached_docs) == 3
186+
assert all([doc.user_data["llm_io"]["llm"]] for doc in cached_docs)

0 commit comments

Comments
 (0)