File size: 1,824 Bytes
0000c5e cade3d1 0000c5e cade3d1 0000c5e cade3d1 0000c5e cade3d1 0000c5e cade3d1 0000c5e cade3d1 0000c5e |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 |
'''Collection of function for RAG on article texts.'''
import os
import logging
import queue
from semantic_text_splitter import TextSplitter
from tokenizers import Tokenizer
from upstash_vector import Index
def ingest(rag_ingest_queue: queue.Queue) -> None:
'''Semantically chunks article and upsert to Upstash vector db
using article title as namespace.'''
logger = logging.getLogger(__name__ + '.ingest()')
index = Index(
url='https://living-whale-89944-us1-vector.upstash.io',
token=os.environ['UPSTASH_VECTOR_KEY']
)
while True:
namespaces = index.list_namespaces()
item = rag_ingest_queue.get()
logger.info(item)
title = item['title']
if title not in namespaces:
text = item['content']
logger.info('Got "%s" from RAG ingest queue', title)
tokenizer=Tokenizer.from_pretrained('bert-base-uncased')
splitter=TextSplitter.from_huggingface_tokenizer(tokenizer, 256)
chunks=splitter.chunks(text)
for i, chunk in enumerate(chunks):
# index.upsert(
# vectors=[
# Vector(
# id=hash(f'{title}-{i}'),
# data=chunk,
# )
# ],
# namespace=title
# )
index.upsert(
[
(
hash(f'{title}-{i}'),
chunk,
{'namespace': title}
)
],
)
logger.info('Ingested %s chunks into vector DB', i + 1)
else:
logger.info('%s already in RAG namespace', title)
|