File size: 7,491 Bytes
5ddcfe5 |
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 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 |
import asyncio
import json
import pdb
import pickle
from typing import Dict, List
import instructor
import logfire
import tiktoken
from anthropic import AsyncAnthropic
from dotenv import load_dotenv
# from instructor import AsyncInstructor, Mode, patch
from jinja2 import Template
from llama_index.core import Document
from llama_index.core.ingestion import IngestionPipeline
from llama_index.core.node_parser import SentenceSplitter
from llama_index.core.schema import TextNode
from openai import AsyncOpenAI
from pydantic import BaseModel, Field
from tenacity import retry, stop_after_attempt, wait_exponential
from tqdm.asyncio import tqdm
load_dotenv(".env")
# logfire.configure()
def create_docs(input_file: str) -> List[Document]:
with open(input_file, "r") as f:
documents: list[Document] = []
for line in f:
data = json.loads(line)
documents.append(
Document(
doc_id=data["doc_id"],
text=data["content"],
metadata={ # type: ignore
"url": data["url"],
"title": data["name"],
"tokens": data["tokens"],
"retrieve_doc": data["retrieve_doc"],
"source": data["source"],
},
excluded_llm_metadata_keys=[
"title",
"tokens",
"retrieve_doc",
"source",
],
excluded_embed_metadata_keys=[
"url",
"tokens",
"retrieve_doc",
"source",
],
)
)
return documents
class SituatedContext(BaseModel):
title: str = Field(..., description="The title of the document.")
context: str = Field(
..., description="The context to situate the chunk within the document."
)
# client = AsyncInstructor(
# client=AsyncAnthropic(),
# create=patch(
# create=AsyncAnthropic().beta.prompt_caching.messages.create,
# mode=Mode.ANTHROPIC_TOOLS,
# ),
# mode=Mode.ANTHROPIC_TOOLS,
# )
aclient = AsyncOpenAI()
# logfire.instrument_openai(aclient)
client: instructor.AsyncInstructor = instructor.from_openai(aclient)
@retry(stop=stop_after_attempt(5), wait=wait_exponential(multiplier=1, min=4, max=10))
async def situate_context(doc: str, chunk: str) -> str:
template = Template(
"""
<document>
{{ doc }}
</document>
Here is the chunk we want to situate within the whole document above:
<chunk>
{{ chunk }}
</chunk>
Please give a short succinct context to situate this chunk within the overall document for the purposes of improving search retrieval of the chunk.
Answer only with the succinct context and nothing else.
"""
)
content = template.render(doc=doc, chunk=chunk)
response = await client.chat.completions.create(
model="gpt-4o-mini",
max_tokens=1000,
temperature=0,
messages=[
{
"role": "user",
"content": content,
}
],
response_model=SituatedContext,
)
return response.context
# async def process_chunk(node: TextNode, document_dict: dict) -> TextNode:
# doc_id: str = node.source_node.node_id # type: ignore
# doc: Document = document_dict[doc_id]
# if doc.metadata["tokens"] > 120_000:
# # Tokenize the document text
# encoding = tiktoken.encoding_for_model("gpt-4o-mini")
# tokens = encoding.encode(doc.text)
# # Trim to 120,000 tokens
# trimmed_tokens = tokens[:120_000]
# # Decode back to text
# trimmed_text = encoding.decode(trimmed_tokens)
# # Update the document text
# doc.text = trimmed_text
# doc.metadata["tokens"] = 120_000
# context: str = await situate_context(doc.text, node.text)
# node.text = f"{node.text}\n\n{context}"
# return node
async def process_chunk(node: TextNode, document_dict: dict) -> TextNode:
doc_id: str = node.source_node.node_id # type: ignore
doc: Document = document_dict[doc_id]
if doc.metadata["tokens"] > 120_000:
# Tokenize the document text
encoding = tiktoken.encoding_for_model("gpt-4o-mini")
tokens = encoding.encode(doc.get_content())
# Trim to 120,000 tokens
trimmed_tokens = tokens[:120_000]
# Decode back to text
trimmed_text = encoding.decode(trimmed_tokens)
# Update the document with trimmed text
doc = Document(text=trimmed_text, metadata=doc.metadata)
doc.metadata["tokens"] = 120_000
context: str = await situate_context(doc.get_content(), node.text)
node.text = f"{node.text}\n\n{context}"
return node
async def process(
documents: List[Document], semaphore_limit: int = 50
) -> List[TextNode]:
# From the document, we create chunks
pipeline = IngestionPipeline(
transformations=[SentenceSplitter(chunk_size=800, chunk_overlap=0)]
)
all_nodes: list[TextNode] = pipeline.run(documents=documents, show_progress=True)
print(f"Number of nodes: {len(all_nodes)}")
document_dict: dict[str, Document] = {doc.doc_id: doc for doc in documents}
semaphore = asyncio.Semaphore(semaphore_limit)
async def process_with_semaphore(node):
async with semaphore:
result = await process_chunk(node, document_dict)
await asyncio.sleep(0.1)
return result
tasks = [process_with_semaphore(node) for node in all_nodes]
results: List[TextNode] = await tqdm.gather(*tasks, desc="Processing chunks")
# results: List[TextNode] = []
# # Add tqdm progress bar with semaphore limit
# for task in tqdm(
# asyncio.as_completed(tasks), total=len(tasks), desc="Processing chunks"
# ):
# result = await task
# results.append(result)
# pdb.set_trace()
return results
async def main():
documents: List[Document] = create_docs("data/all_sources_data.jsonl")
enhanced_nodes: List[TextNode] = await process(documents)
with open("data/all_sources_contextual_nodes.pkl", "wb") as f:
pickle.dump(enhanced_nodes, f)
# pipeline = IngestionPipeline(
# transformations=[SentenceSplitter(chunk_size=800, chunk_overlap=0)]
# )
# all_nodes: list[TextNode] = pipeline.run(documents=documents, show_progress=True)
# print(all_nodes[7933])
# pdb.set_trace()
with open("data/all_sources_contextual_nodes.pkl", "rb") as f:
enhanced_nodes: list[TextNode] = pickle.load(f)
for i, node in enumerate(enhanced_nodes):
print(f"Chunk {i + 1}:")
print(f"Node: {node}")
print(f"Text: {node.text}")
# pdb.set_trace()
break
if __name__ == "__main__":
asyncio.run(main())
# Ok so I need to create a new chroma-db-all_sources that embedded (context+chunk)
# I need to create an index and instead of from_documents it will be from_nodes
# First I need to create contexts for each chunk. Create a list of tasks (doc + chunk)
# documents = create_docs("data/all_sources_data.jsonl")
# pipeline = IngestionPipeline(
# transformations=[SentenceSplitter(chunk_size=800, chunk_overlap=0)]
# )
# all_nodes = pipeline.run(documents=documents, show_progress=True)
|