Nullpointer-KK commited on
Commit
f8a4cda
·
unverified ·
1 Parent(s): f741b58

Add files via upload

Browse files
scripts/custom_retriever.py ADDED
@@ -0,0 +1,257 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import asyncio
2
+ import os
3
+ import time
4
+ import traceback
5
+ from typing import List, Optional
6
+
7
+ import logfire
8
+ import tiktoken
9
+ from cohere import AsyncClient
10
+ from dotenv import load_dotenv
11
+ from llama_index.core import Document, QueryBundle
12
+ from llama_index.core.async_utils import run_async_tasks
13
+ from llama_index.core.callbacks import CBEventType, EventPayload
14
+ from llama_index.core.retrievers import (
15
+ BaseRetriever,
16
+ KeywordTableSimpleRetriever,
17
+ VectorIndexRetriever,
18
+ )
19
+ from llama_index.core.schema import MetadataMode, NodeWithScore, QueryBundle, TextNode
20
+ from llama_index.core.vector_stores import (
21
+ FilterCondition,
22
+ FilterOperator,
23
+ MetadataFilter,
24
+ MetadataFilters,
25
+ )
26
+ from llama_index.postprocessor.cohere_rerank import CohereRerank
27
+ from llama_index.postprocessor.cohere_rerank.base import CohereRerank
28
+
29
+ load_dotenv()
30
+
31
+
32
+ class AsyncCohereRerank(CohereRerank):
33
+ def __init__(
34
+ self,
35
+ top_n: int = 5,
36
+ model: str = "rerank-english-v3.0",
37
+ api_key: Optional[str] = None,
38
+ ) -> None:
39
+ super().__init__(top_n=top_n, model=model, api_key=api_key)
40
+ self._api_key = api_key
41
+ self._model = model
42
+ self._top_n = top_n
43
+
44
+ async def apostprocess_nodes(
45
+ self,
46
+ nodes: List[NodeWithScore],
47
+ query_bundle: Optional[QueryBundle] = None,
48
+ ) -> List[NodeWithScore]:
49
+ if query_bundle is None:
50
+ raise ValueError("Query bundle must be provided.")
51
+
52
+ if len(nodes) == 0:
53
+ return []
54
+
55
+ async_client = AsyncClient(api_key=self._api_key)
56
+
57
+ with self.callback_manager.event(
58
+ CBEventType.RERANKING,
59
+ payload={
60
+ EventPayload.NODES: nodes,
61
+ EventPayload.MODEL_NAME: self._model,
62
+ EventPayload.QUERY_STR: query_bundle.query_str,
63
+ EventPayload.TOP_K: self._top_n,
64
+ },
65
+ ) as event:
66
+ texts = [
67
+ node.node.get_content(metadata_mode=MetadataMode.EMBED)
68
+ for node in nodes
69
+ ]
70
+
71
+ results = await async_client.rerank(
72
+ model=self._model,
73
+ top_n=self._top_n,
74
+ query=query_bundle.query_str,
75
+ documents=texts,
76
+ )
77
+
78
+ new_nodes = []
79
+ for result in results.results:
80
+ new_node_with_score = NodeWithScore(
81
+ node=nodes[result.index].node, score=result.relevance_score
82
+ )
83
+ new_nodes.append(new_node_with_score)
84
+ event.on_end(payload={EventPayload.NODES: new_nodes})
85
+
86
+ return new_nodes
87
+
88
+
89
+ class CustomRetriever(BaseRetriever):
90
+ """Custom retriever that performs both semantic search and hybrid search."""
91
+
92
+ def __init__(
93
+ self,
94
+ vector_retriever: VectorIndexRetriever,
95
+ document_dict: dict,
96
+ keyword_retriever=None,
97
+ mode: str = "AND",
98
+ ) -> None:
99
+ """Init params."""
100
+ self._vector_retriever = vector_retriever
101
+ self._document_dict = document_dict
102
+ self._keyword_retriever = keyword_retriever
103
+ if mode not in ("AND", "OR"):
104
+ raise ValueError("Invalid mode.")
105
+ self._mode = mode
106
+ super().__init__()
107
+
108
+ async def _process_retrieval(
109
+ self, query_bundle: QueryBundle, is_async: bool = True
110
+ ) -> List[NodeWithScore]:
111
+ """Common processing logic for both sync and async retrieval."""
112
+ # Clean query string
113
+ query_bundle.query_str = query_bundle.query_str.replace(
114
+ "\ninput is ", ""
115
+ ).rstrip()
116
+ logfire.info(f"Retrieving nodes with string: '{query_bundle}'")
117
+
118
+ start = time.time()
119
+
120
+ # Get nodes from both retrievers
121
+ if is_async:
122
+ nodes = await self._vector_retriever.aretrieve(query_bundle)
123
+ else:
124
+ nodes = self._vector_retriever.retrieve(query_bundle)
125
+
126
+ keyword_nodes = []
127
+ if self._keyword_retriever:
128
+ if is_async:
129
+ keyword_nodes = await self._keyword_retriever.aretrieve(query_bundle)
130
+ else:
131
+ keyword_nodes = self._keyword_retriever.retrieve(query_bundle)
132
+
133
+ logfire.info(f"Number of vector nodes: {len(nodes)}")
134
+ logfire.info(f"Number of keyword nodes: {len(keyword_nodes)}")
135
+
136
+ # # Filter keyword nodes based on metadata filters from vector retriever
137
+ # if (
138
+ # hasattr(self._vector_retriever, "_filters")
139
+ # and self._vector_retriever._filters
140
+ # ):
141
+ # filtered_keyword_nodes = []
142
+ # for node in keyword_nodes:
143
+ # node_source = node.node.metadata.get("source")
144
+ # # Check if node's source matches any of the filter conditions
145
+ # for filter in self._vector_retriever._filters.filters:
146
+ # if (
147
+ # isinstance(filter, MetadataFilter)
148
+ # and filter.key == "source"
149
+ # and filter.operator == FilterOperator.EQ
150
+ # and filter.value == node_source
151
+ # ):
152
+ # filtered_keyword_nodes.append(node)
153
+ # break
154
+ # keyword_nodes = filtered_keyword_nodes
155
+ # logfire.info(
156
+ # f"Number of keyword nodes after filtering: {len(keyword_nodes)}"
157
+ # )
158
+
159
+ # Combine results based on mode
160
+ vector_ids = {n.node.node_id for n in nodes}
161
+ keyword_ids = {n.node.node_id for n in keyword_nodes}
162
+ combined_dict = {n.node.node_id: n for n in nodes}
163
+ combined_dict.update({n.node.node_id: n for n in keyword_nodes})
164
+
165
+ # If no keyword retriever or no keyword nodes, just use vector nodes
166
+ if not self._keyword_retriever or not keyword_nodes:
167
+ retrieve_ids = vector_ids
168
+ else:
169
+ retrieve_ids = (
170
+ vector_ids.intersection(keyword_ids)
171
+ if self._mode == "AND"
172
+ else vector_ids.union(keyword_ids)
173
+ )
174
+
175
+ nodes = [combined_dict[rid] for rid in retrieve_ids]
176
+ logfire.info(f"Number of combined nodes: {len(nodes)}")
177
+
178
+ # Filter unique doc IDs
179
+ nodes = self._filter_nodes_by_unique_doc_id(nodes)
180
+ logfire.info(f"Number of nodes without duplicate doc IDs: {len(nodes)}")
181
+
182
+ # Process node contents
183
+ for node in nodes:
184
+ doc_id = node.node.source_node.node_id
185
+ if node.metadata["retrieve_doc"]:
186
+ doc = self._document_dict[doc_id]
187
+ node.node.text = doc.text
188
+ node.node.node_id = doc_id
189
+
190
+ # Rerank results
191
+ try:
192
+ reranker = (
193
+ AsyncCohereRerank(top_n=5, model="rerank-english-v3.0")
194
+ if is_async
195
+ else CohereRerank(top_n=5, model="rerank-english-v3.0")
196
+ )
197
+ nodes = (
198
+ await reranker.apostprocess_nodes(nodes, query_bundle)
199
+ if is_async
200
+ else reranker.postprocess_nodes(nodes, query_bundle)
201
+ )
202
+ except Exception as e:
203
+ error_msg = f"Error during reranking: {type(e).__name__}: {str(e)}\n"
204
+ error_msg += "Traceback:\n"
205
+ error_msg += traceback.format_exc()
206
+ logfire.error(error_msg)
207
+
208
+ # Filter by score and token count
209
+ nodes_filtered = self._filter_by_score_and_tokens(nodes)
210
+
211
+ duration = time.time() - start
212
+ logfire.info(f"Retrieving nodes took {duration:.2f}s")
213
+ logfire.info(f"Nodes sent to LLM: {nodes_filtered[:5]}")
214
+
215
+ return nodes_filtered[:5]
216
+
217
+ def _filter_nodes_by_unique_doc_id(
218
+ self, nodes: List[NodeWithScore]
219
+ ) -> List[NodeWithScore]:
220
+ """Filter nodes to keep only unique doc IDs."""
221
+ unique_nodes = {}
222
+ for node in nodes:
223
+ doc_id = node.node.source_node.node_id
224
+ if doc_id is not None and doc_id not in unique_nodes:
225
+ unique_nodes[doc_id] = node
226
+ return list(unique_nodes.values())
227
+
228
+ def _filter_by_score_and_tokens(
229
+ self, nodes: List[NodeWithScore]
230
+ ) -> List[NodeWithScore]:
231
+ """Filter nodes by score and token count."""
232
+ nodes_filtered = []
233
+ total_tokens = 0
234
+ enc = tiktoken.encoding_for_model("gpt-4o-mini")
235
+
236
+ for node in nodes:
237
+ if node.score < 0.10:
238
+ logfire.info(f"Skipping node with score {node.score}")
239
+ continue
240
+
241
+ node_tokens = len(enc.encode(node.node.text))
242
+ if total_tokens + node_tokens > 100_000:
243
+ logfire.info("Skipping node due to token count exceeding 100k")
244
+ break
245
+
246
+ total_tokens += node_tokens
247
+ nodes_filtered.append(node)
248
+
249
+ return nodes_filtered
250
+
251
+ async def _aretrieve(self, query_bundle: QueryBundle) -> List[NodeWithScore]:
252
+ """Async retrieve nodes given query."""
253
+ return await self._process_retrieval(query_bundle, is_async=True)
254
+
255
+ def _retrieve(self, query_bundle: QueryBundle) -> List[NodeWithScore]:
256
+ """Sync retrieve nodes given query."""
257
+ return asyncio.run(self._process_retrieval(query_bundle, is_async=False))
scripts/evaluate_rag_system.py ADDED
@@ -0,0 +1,773 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import asyncio
2
+ import html
3
+ import json
4
+ import logging
5
+ import os
6
+ import pdb
7
+ import pickle
8
+ import random
9
+ import time
10
+ from typing import Dict, List, Optional, Tuple
11
+
12
+ import aiofiles
13
+ import chromadb
14
+ import logfire
15
+ import pandas as pd
16
+ from custom_retriever import CustomRetriever
17
+ from llama_index.agent.openai import OpenAIAgent
18
+ from llama_index.core import Document, SimpleKeywordTableIndex, VectorStoreIndex
19
+ from llama_index.core.base.base_retriever import BaseRetriever
20
+ from llama_index.core.bridge.pydantic import Field, SerializeAsAny
21
+ from llama_index.core.chat_engine.types import (
22
+ AGENT_CHAT_RESPONSE_TYPE,
23
+ AgentChatResponse,
24
+ ChatResponseMode,
25
+ )
26
+ from llama_index.core.evaluation import (
27
+ AnswerRelevancyEvaluator,
28
+ BatchEvalRunner,
29
+ EmbeddingQAFinetuneDataset,
30
+ FaithfulnessEvaluator,
31
+ RelevancyEvaluator,
32
+ )
33
+ from llama_index.core.evaluation.base import EvaluationResult
34
+ from llama_index.core.evaluation.retrieval.base import (
35
+ BaseRetrievalEvaluator,
36
+ RetrievalEvalMode,
37
+ RetrievalEvalResult,
38
+ )
39
+ from llama_index.core.indices.base_retriever import BaseRetriever
40
+ from llama_index.core.ingestion import IngestionPipeline
41
+ from llama_index.core.node_parser import SentenceSplitter
42
+ from llama_index.core.postprocessor.types import BaseNodePostprocessor
43
+ from llama_index.core.retrievers import (
44
+ BaseRetriever,
45
+ KeywordTableSimpleRetriever,
46
+ VectorIndexRetriever,
47
+ )
48
+ from llama_index.core.schema import ImageNode, NodeWithScore, QueryBundle, TextNode
49
+ from llama_index.core.tools import RetrieverTool, ToolMetadata
50
+ from llama_index.core.vector_stores import (
51
+ FilterOperator,
52
+ MetadataFilter,
53
+ MetadataFilters,
54
+ )
55
+ from llama_index.embeddings.cohere import CohereEmbedding
56
+ from llama_index.embeddings.openai import OpenAIEmbedding
57
+ from llama_index.llms.gemini import Gemini
58
+ from llama_index.llms.openai import OpenAI
59
+ from llama_index.vector_stores.chroma import ChromaVectorStore
60
+ from prompts import system_message_openai_agent
61
+ from pydantic import BaseModel, Field
62
+ from tqdm.asyncio import tqdm_asyncio
63
+
64
+ # from setup import (
65
+ # AVAILABLE_SOURCES,
66
+ # AVAILABLE_SOURCES_UI,
67
+ # custom_retriever_all_sources,
68
+ # custom_retriever_langchain,
69
+ # custom_retriever_llama_index,
70
+ # custom_retriever_openai_cookbooks,
71
+ # custom_retriever_peft,
72
+ # custom_retriever_transformers,
73
+ # custom_retriever_trl,
74
+ # )
75
+
76
+
77
+ class RotatingJSONLWriter:
78
+ def __init__(
79
+ self, base_filename: str, max_size: int = 10**6, backup_count: int = 5
80
+ ):
81
+ """
82
+ Initialize the rotating JSONL writer.
83
+
84
+ Args:
85
+ base_filename (str): The base filename for the JSONL files.
86
+ max_size (int): Maximum size in bytes before rotating.
87
+ backup_count (int): Number of backup files to keep.
88
+ """
89
+ self.base_filename = base_filename
90
+ self.max_size = max_size
91
+ self.backup_count = backup_count
92
+ self.current_file = base_filename
93
+
94
+ async def write(self, data: dict):
95
+ # Rotate if file exceeds max size
96
+ if (
97
+ os.path.exists(self.current_file)
98
+ and os.path.getsize(self.current_file) > self.max_size
99
+ ):
100
+ await self.rotate_files()
101
+
102
+ async with aiofiles.open(self.current_file, "a", encoding="utf-8") as f:
103
+ await f.write(json.dumps(data, ensure_ascii=False) + "\n")
104
+
105
+ async def rotate_files(self):
106
+ # Remove the oldest backup if it exists
107
+ oldest_backup = f"{self.base_filename}.{self.backup_count}"
108
+ if os.path.exists(oldest_backup):
109
+ os.remove(oldest_backup)
110
+
111
+ # Rotate existing backups
112
+ for i in range(self.backup_count - 1, 0, -1):
113
+ src = f"{self.base_filename}.{i}"
114
+ dst = f"{self.base_filename}.{i + 1}"
115
+ if os.path.exists(src):
116
+ os.rename(src, dst)
117
+
118
+ # Rename current file to backup
119
+ os.rename(self.current_file, f"{self.base_filename}.1")
120
+
121
+
122
+ class AsyncKeywordTableSimpleRetriever(KeywordTableSimpleRetriever):
123
+ async def _aretrieve(self, query_bundle: QueryBundle) -> List[NodeWithScore]:
124
+ loop = asyncio.get_event_loop()
125
+ return await loop.run_in_executor(None, self._retrieve, query_bundle)
126
+
127
+
128
+ class SampleableEmbeddingQADataset:
129
+ def __init__(self, dataset: EmbeddingQAFinetuneDataset):
130
+ self.dataset = dataset
131
+
132
+ def sample(self, n: int) -> EmbeddingQAFinetuneDataset:
133
+ """
134
+ Sample n queries from the dataset.
135
+
136
+ Args:
137
+ n (int): Number of queries to sample.
138
+
139
+ Returns:
140
+ EmbeddingQAFinetuneDataset: A new dataset with the sampled queries.
141
+ """
142
+ if n > len(self.dataset.queries):
143
+ raise ValueError(
144
+ f"n ({n}) is greater than the number of queries ({len(self.dataset.queries)})"
145
+ )
146
+
147
+ sampled_query_ids = random.sample(list(self.dataset.queries.keys()), n)
148
+
149
+ sampled_queries = {qid: self.dataset.queries[qid] for qid in sampled_query_ids}
150
+ sampled_relevant_docs = {
151
+ qid: self.dataset.relevant_docs[qid] for qid in sampled_query_ids
152
+ }
153
+
154
+ # Collect all unique document IDs from the sampled relevant docs
155
+ sampled_doc_ids = set()
156
+ for doc_ids in sampled_relevant_docs.values():
157
+ sampled_doc_ids.update(doc_ids)
158
+
159
+ sampled_corpus = {
160
+ doc_id: self.dataset.corpus[doc_id] for doc_id in sampled_doc_ids
161
+ }
162
+
163
+ return EmbeddingQAFinetuneDataset(
164
+ queries=sampled_queries,
165
+ corpus=sampled_corpus,
166
+ relevant_docs=sampled_relevant_docs,
167
+ mode=self.dataset.mode,
168
+ )
169
+
170
+ def __getattr__(self, name):
171
+ return getattr(self.dataset, name)
172
+
173
+
174
+ class RetrieverEvaluator(BaseRetrievalEvaluator):
175
+ """Retriever evaluator.
176
+
177
+ This module will evaluate a retriever using a set of metrics.
178
+
179
+ Args:
180
+ metrics (List[BaseRetrievalMetric]): Sequence of metrics to evaluate
181
+ retriever: Retriever to evaluate.
182
+ node_postprocessors (Optional[List[BaseNodePostprocessor]]): Post-processor to apply after retrieval.
183
+ """
184
+
185
+ retriever: BaseRetriever = Field(..., description="Retriever to evaluate")
186
+ node_postprocessors: Optional[List[SerializeAsAny[BaseNodePostprocessor]]] = Field(
187
+ default=None, description="Optional post-processor"
188
+ )
189
+
190
+ async def _aget_retrieved_ids_and_texts(
191
+ self,
192
+ query: str,
193
+ mode: RetrievalEvalMode = RetrievalEvalMode.TEXT,
194
+ source: str = "",
195
+ ) -> Tuple[List[str], List[str]]:
196
+ """Get retrieved ids and texts, potentially applying a post-processor."""
197
+ try:
198
+ retrieved_nodes: list[NodeWithScore] = await self.retriever.aretrieve(query)
199
+ logfire.info(f"Retrieved {len(retrieved_nodes)} nodes for: '{query}'")
200
+ except Exception as e:
201
+ return ["00000000-0000-0000-0000-000000000000"], [str(e)]
202
+
203
+ if len(retrieved_nodes) == 0 or retrieved_nodes is None:
204
+ print(f"No nodes retrieved for {query}")
205
+ return ["00000000-0000-0000-0000-000000000000"], ["No nodes retrieved"]
206
+
207
+ if self.node_postprocessors:
208
+ for node_postprocessor in self.node_postprocessors:
209
+ retrieved_nodes = node_postprocessor.postprocess_nodes(
210
+ retrieved_nodes, query_str=query
211
+ )
212
+
213
+ return (
214
+ [node.node.node_id for node in retrieved_nodes],
215
+ [node.node.text for node in retrieved_nodes], # type: ignore
216
+ )
217
+
218
+
219
+ class OpenAIAgentRetrieverEvaluator(BaseRetrievalEvaluator):
220
+ agent: OpenAIAgent = Field(description="The OpenAI agent used for retrieval")
221
+
222
+ async def _aget_retrieved_ids_and_texts(
223
+ self,
224
+ query: str,
225
+ mode: RetrievalEvalMode = RetrievalEvalMode.TEXT,
226
+ source: str = "",
227
+ ) -> Tuple[List[str], List[str]]:
228
+
229
+ self.agent.memory.reset()
230
+
231
+ try:
232
+ logfire.info(f"Executing agent with query: {query}")
233
+ response: AgentChatResponse = await self.agent.achat(query)
234
+ except Exception as e:
235
+ # await self._save_response_data_async(
236
+ # source, query, ["Error retrieving nodes"], "Error retrieving nodes"
237
+ # )
238
+ return ["00000000-0000-0000-0000-000000000000"], [str(e)]
239
+
240
+ retrieved_nodes: list[NodeWithScore] = get_nodes_with_score(response)
241
+ logfire.info(f"Retrieved {len(retrieved_nodes)} to answer: '{query}'")
242
+ retrieved_nodes = retrieved_nodes[:6] # Limit to first 6 retrieved nodes
243
+
244
+ if len(retrieved_nodes) == 0 or retrieved_nodes is None:
245
+ # await self._save_response_data_async(
246
+ # source, query, ["No retrieved nodes"], "No retrieved nodes"
247
+ # )
248
+ return ["00000000-0000-0000-0000-000000000000"], ["No nodes retrieved"]
249
+
250
+ retrieved_ids = [node.node.node_id for node in retrieved_nodes]
251
+ retrieved_texts = [node.node.text for node in retrieved_nodes] # type: ignore
252
+
253
+ # Will not save context as its too long (token wise), costly and takes too much time.
254
+ await self._save_response_data_async(
255
+ source=source, query=query, context="", response=response.response
256
+ )
257
+
258
+ return retrieved_ids, retrieved_texts
259
+
260
+ async def _save_response_data_async(self, source, query, context, response):
261
+ data = {
262
+ "source": source,
263
+ "question": query,
264
+ # "context": context,
265
+ "answer": response,
266
+ }
267
+ await rotating_writer.write(data)
268
+
269
+
270
+ def get_nodes_with_score(completion) -> list[NodeWithScore]:
271
+ retrieved_nodes = []
272
+ for source in completion.sources: # completion.sources = list[ToolOutput]
273
+ if source.is_error == True:
274
+ continue
275
+ for node in source.raw_output: # source.raw_output = list[NodeWithScore]
276
+ retrieved_nodes.append(node)
277
+ return retrieved_nodes
278
+
279
+
280
+ def setup_basic_database(db_collection, dict_file_name, keyword_retriever):
281
+ db = chromadb.PersistentClient(path=f"data/{db_collection}")
282
+ chroma_collection = db.get_or_create_collection(db_collection)
283
+ vector_store = ChromaVectorStore(chroma_collection=chroma_collection)
284
+
285
+ # embed_model = OpenAIEmbedding(model="text-embedding-3-large", mode="similarity")
286
+ embed_model = CohereEmbedding(
287
+ api_key=os.environ["COHERE_API_KEY"],
288
+ model_name="embed-english-v3.0",
289
+ input_type="search_query",
290
+ )
291
+ # client = embed_model._get_client()
292
+ # aclient = embed_model._get_aclient()
293
+ # logfire.instrument_openai(client)
294
+ # logfire.instrument_openai(aclient)
295
+
296
+ index = VectorStoreIndex.from_vector_store(
297
+ vector_store=vector_store,
298
+ show_progress=True,
299
+ )
300
+ vector_retriever = VectorIndexRetriever(
301
+ index=index,
302
+ similarity_top_k=15,
303
+ embed_model=embed_model,
304
+ )
305
+ with open(f"data/{db_collection}/{dict_file_name}", "rb") as f:
306
+ document_dict = pickle.load(f)
307
+
308
+ return CustomRetriever(vector_retriever, document_dict, keyword_retriever, "OR")
309
+
310
+
311
+ def update_query_engine_tools(selected_sources, custom_retriever_all_sources):
312
+ tools = []
313
+ source_mapping = {
314
+ # "Transformers Docs": (
315
+ # custom_retriever_transformers,
316
+ # "Transformers_information",
317
+ # """Useful for general questions asking about the artificial intelligence (AI) field. Employ this tool to fetch information on topics such as language models (LLMs) models such as Llama3 and theory (transformer architectures), tips on prompting, quantization, etc.""",
318
+ # ),
319
+ # "PEFT Docs": (
320
+ # custom_retriever_peft,
321
+ # "PEFT_information",
322
+ # """Useful for questions asking about efficient LLM fine-tuning. Employ this tool to fetch information on topics such as LoRA, QLoRA, etc.""",
323
+ # ),
324
+ # "TRL Docs": (
325
+ # custom_retriever_trl,
326
+ # "TRL_information",
327
+ # """Useful for questions asking about fine-tuning LLMs with reinforcement learning (RLHF). Includes information about the Supervised Fine-tuning step (SFT), Reward Modeling step (RM), and the Proximal Policy Optimization (PPO) step.""",
328
+ # ),
329
+ # "LlamaIndex Docs": (
330
+ # custom_retriever_llama_index,
331
+ # "LlamaIndex_information",
332
+ # """Useful for questions asking about retrieval augmented generation (RAG) with LLMs and embedding models. It is the documentation of a framework, includes info about fine-tuning embedding models, building chatbots, and agents with llms, using vector databases, embeddings, information retrieval with cosine similarity or bm25, etc.""",
333
+ # ),
334
+ # "OpenAI Cookbooks": (
335
+ # custom_retriever_openai_cookbooks,
336
+ # "openai_cookbooks_info",
337
+ # """Useful for questions asking about accomplishing common tasks with the OpenAI API. Returns example code and guides stored in Jupyter notebooks, including info about ChatGPT GPT actions, OpenAI Assistants API, and How to fine-tune OpenAI's GPT-4o and GPT-4o-mini models with the OpenAI API.""",
338
+ # ),
339
+ # "LangChain Docs": (
340
+ # custom_retriever_langchain,
341
+ # "langchain_info",
342
+ # """Useful for questions asking about the LangChain framework. It is the documentation of the LangChain framework, includes info about building chains, agents, and tools, using memory, prompts, callbacks, etc.""",
343
+ # ),
344
+ "All Sources": (
345
+ custom_retriever_all_sources,
346
+ "all_sources_info",
347
+ """Useful for all questions, contains information about the field of AI.""",
348
+ ),
349
+ }
350
+
351
+ for source in selected_sources:
352
+ if source in source_mapping:
353
+ retriever, name, description = source_mapping[source]
354
+ tools.append(
355
+ RetrieverTool(
356
+ retriever=retriever,
357
+ metadata=ToolMetadata(
358
+ name=name,
359
+ description=description,
360
+ ),
361
+ )
362
+ )
363
+
364
+ return tools
365
+
366
+
367
+ def setup_agent(custom_retriever_all_sources) -> OpenAIAgent:
368
+
369
+ llm = OpenAI(
370
+ temperature=1,
371
+ # model="gpt-4o",
372
+ model="gpt-4o-mini",
373
+ max_tokens=5000,
374
+ max_retries=3,
375
+ )
376
+ client = llm._get_client()
377
+ logfire.instrument_openai(client)
378
+ aclient = llm._get_aclient()
379
+ logfire.instrument_openai(aclient)
380
+
381
+ tools_available = [
382
+ # "Transformers Docs",
383
+ # "PEFT Docs",
384
+ # "TRL Docs",
385
+ # "LlamaIndex Docs",
386
+ # "LangChain Docs",
387
+ # "OpenAI Cookbooks",
388
+ "All Sources",
389
+ ]
390
+ query_engine_tools = update_query_engine_tools(
391
+ tools_available, custom_retriever_all_sources
392
+ )
393
+
394
+ agent = OpenAIAgent.from_tools(
395
+ llm=llm,
396
+ tools=query_engine_tools,
397
+ system_prompt=system_message_openai_agent,
398
+ )
399
+
400
+ return agent
401
+
402
+
403
+ async def evaluate_answers():
404
+ start_time = time.time()
405
+
406
+ # Gemini is not async here, maybe it could work with multithreading?
407
+ # llm = Gemini(model="models/gemini-1.5-flash-002", temperature=1, max_tokens=1000)
408
+ llm = OpenAI(model="gpt-4o-mini", temperature=1, max_tokens=1000)
409
+ relevancy_evaluator = AnswerRelevancyEvaluator(llm=llm)
410
+
411
+ # Load queries and response strings from JSONL file
412
+ query_response_pairs = []
413
+ with open("response_data.jsonl", "r") as f:
414
+ for line in f:
415
+ data = json.loads(line)
416
+ query_response_pairs.append(
417
+ (data["source"], data["query"], data["response"])
418
+ )
419
+
420
+ logfire.info(f"Number of queries and answers: {len(query_response_pairs)}")
421
+
422
+ semaphore = asyncio.Semaphore(90) # Adjust this value as needed
423
+
424
+ async def evaluate_query_response(source, query, response):
425
+ async with semaphore:
426
+ try:
427
+ result: EvaluationResult = await relevancy_evaluator.aevaluate(
428
+ query=query, response=response
429
+ )
430
+ return source, result
431
+ except Exception as e:
432
+ logfire.error(f"Error evaluating query for {source}: {str(e)}")
433
+ return source, None
434
+
435
+ # Use asyncio.gather to run all evaluations concurrently
436
+ results = await tqdm_asyncio.gather(
437
+ *[
438
+ evaluate_query_response(source, query, response)
439
+ for source, query, response in query_response_pairs
440
+ ],
441
+ desc="Evaluating answers",
442
+ total=len(query_response_pairs),
443
+ )
444
+
445
+ # Process results
446
+ eval_results = {}
447
+ for item in results:
448
+ if isinstance(item, tuple) and len(item) == 2:
449
+ source, result = item
450
+ if result is not None:
451
+ if source not in eval_results:
452
+ eval_results[source] = []
453
+ eval_results[source].append(result)
454
+ else:
455
+ logfire.error(f"Unexpected result: {item}")
456
+
457
+ # Save results for each source
458
+ for source, results in eval_results.items():
459
+ with open(f"eval_answers_results_{source}.pkl", "wb") as f:
460
+ pickle.dump(results, f)
461
+
462
+ end_time = time.time()
463
+ logfire.info(f"Total evaluation time: {round(end_time - start_time, 3)} seconds")
464
+
465
+ return eval_results
466
+
467
+
468
+ def create_docs(input_file: str) -> List[Document]:
469
+ with open(input_file, "r") as f:
470
+ documents = []
471
+ for line in f:
472
+ data = json.loads(line)
473
+ documents.append(
474
+ Document(
475
+ doc_id=data["doc_id"],
476
+ text=data["content"],
477
+ metadata={ # type: ignore
478
+ "url": data["url"],
479
+ "title": data["name"],
480
+ "tokens": data["tokens"],
481
+ "retrieve_doc": data["retrieve_doc"],
482
+ "source": data["source"],
483
+ },
484
+ excluded_llm_metadata_keys=[
485
+ "title",
486
+ "tokens",
487
+ "retrieve_doc",
488
+ "source",
489
+ ],
490
+ excluded_embed_metadata_keys=[
491
+ "url",
492
+ "tokens",
493
+ "retrieve_doc",
494
+ "source",
495
+ ],
496
+ )
497
+ )
498
+ return documents
499
+
500
+
501
+ def get_sample_size(source: str, total_queries: int) -> int:
502
+ """Determine the number of queries to sample based on the source."""
503
+ # small_datasets = {"peft": 0, "trl": 0, "openai_cookbooks": 0}
504
+ # large_datasets = {
505
+ # "transformers": 0,
506
+ # "llama_index": 0,
507
+ # "langchain": 1,
508
+ # "tai_blog": 0,
509
+ # }
510
+ small_datasets = {"peft": 49, "trl": 34, "openai_cookbooks": 170}
511
+ large_datasets = {
512
+ "transformers": 200,
513
+ "llama_index": 200,
514
+ "langchain": 200,
515
+ "tai_blog": 200,
516
+ }
517
+ # small_datasets = {"peft": 49, "trl": 34, "openai_cookbooks": 100}
518
+ # large_datasets = {
519
+ # "transformers": 100,
520
+ # "llama_index": 100,
521
+ # "langchain": 100,
522
+ # "tai_blog": 100,
523
+ # }
524
+ # small_datasets = {"peft": 18, "trl": 12, "openai_cookbooks": 14}
525
+ # large_datasets = {
526
+ # "transformers": 24,
527
+ # "llama_index": 8,
528
+ # "langchain": 6,
529
+ # "tai_blog": 18,
530
+ # }
531
+ # small_datasets = {"peft": 4, "trl": 4, "openai_cookbooks": 4}
532
+ # large_datasets = {
533
+ # "transformers": 4,
534
+ # "llama_index": 4,
535
+ # "langchain": 5,
536
+ # "tai_blog": 5,
537
+ # }
538
+
539
+ if source in small_datasets:
540
+ return small_datasets[source]
541
+ elif source in large_datasets:
542
+ return large_datasets[source]
543
+ else:
544
+ return min(100, total_queries) # Default to 100 or all queries if less than 100
545
+
546
+
547
+ async def evaluate_retriever():
548
+ start_time = time.time()
549
+ with open("data/keyword_retriever_async.pkl", "rb") as f:
550
+ keyword_retriever = pickle.load(f)
551
+
552
+ custom_retriever_all_sources: CustomRetriever = setup_basic_database(
553
+ "chroma-db-all_sources", "document_dict_all_sources.pkl", keyword_retriever
554
+ )
555
+ # agent = setup_agent(custom_retriever_all_sources)
556
+
557
+ # filters = MetadataFilters(
558
+ # filters=[
559
+ # MetadataFilter(key="source", operator=FilterOperator.EQ, value="langchain"),
560
+ # ]
561
+ # )
562
+ # custom_retriever_all_sources._vector_retriever._filters = filters
563
+
564
+ end_time = time.time()
565
+ logfire.info(
566
+ f"Time taken for setup the custom retriever: {round(end_time - start_time, 2)} seconds"
567
+ )
568
+
569
+ sources_to_evaluate = [
570
+ "transformers",
571
+ "peft",
572
+ "trl",
573
+ "llama_index",
574
+ "langchain",
575
+ "openai_cookbooks",
576
+ "tai_blog",
577
+ ]
578
+
579
+ # for k in [5, 7, 9, 11, 13, 15]:
580
+ # custom_retriever_all_sources._vector_retriever._similarity_top_k = k
581
+
582
+ retriever_evaluator = RetrieverEvaluator.from_metric_names(
583
+ ["mrr", "hit_rate"], retriever=custom_retriever_all_sources
584
+ )
585
+ # retriever_evaluator = OpenAIAgentRetrieverEvaluator.from_metric_names(
586
+ # metric_names=["mrr", "hit_rate"], agent=agent
587
+ # )
588
+
589
+ all_query_pairs = []
590
+ for source in sources_to_evaluate:
591
+ rag_eval_dataset = EmbeddingQAFinetuneDataset.from_json(
592
+ f"scripts/rag_eval_{source}.json"
593
+ )
594
+ sampleable_dataset = SampleableEmbeddingQADataset(rag_eval_dataset)
595
+ sample_size = get_sample_size(source, len(sampleable_dataset.queries))
596
+ sampled_dataset = sampleable_dataset.sample(n=sample_size)
597
+ query_expected_ids_pairs = sampled_dataset.query_docid_pairs
598
+ all_query_pairs.extend(
599
+ [(source, pair[0], pair[1]) for pair in query_expected_ids_pairs]
600
+ )
601
+
602
+ semaphore = asyncio.Semaphore(220) # 250 caused a couple of errors
603
+ # semaphore = asyncio.Semaphore(90) # 100 caused a couple of errors with agent
604
+
605
+ async def evaluate_query(source, query, expected_ids):
606
+ async with semaphore:
607
+ try:
608
+ result: RetrievalEvalResult = await retriever_evaluator.aevaluate(
609
+ query=query,
610
+ expected_ids=expected_ids,
611
+ mode=RetrievalEvalMode.TEXT,
612
+ source=source,
613
+ )
614
+ return source, result
615
+ except Exception as e:
616
+ logfire.error(f"Error evaluating query for {source}: {str(e)}")
617
+ return source, None
618
+
619
+ # Use asyncio.gather to run all evaluations concurrently
620
+ results = await tqdm_asyncio.gather(
621
+ *[
622
+ evaluate_query(source, query, expected_ids)
623
+ for source, query, expected_ids in all_query_pairs
624
+ ],
625
+ desc="Evaluating queries",
626
+ total=len(all_query_pairs),
627
+ )
628
+
629
+ # Process results
630
+ eval_results = {source: [] for source in sources_to_evaluate}
631
+ for item in results:
632
+ if isinstance(item, tuple) and len(item) == 2:
633
+ source, result = item
634
+ if result is not None:
635
+ eval_results[source].append(result)
636
+ else:
637
+ logfire.error(f"Unexpected result: {item}")
638
+
639
+ # Save results for each source
640
+ for source, results in eval_results.items():
641
+ with open(f"eval_results_{source}.pkl", "wb") as f:
642
+ pickle.dump(results, f)
643
+ # print(display_results_retriever(source, results))
644
+
645
+ end_time = time.time()
646
+ logfire.info(f"Total evaluation time: {round(end_time - start_time, 3)} seconds")
647
+
648
+
649
+ def display_results_retriever(name, eval_results):
650
+ """Display results from evaluate."""
651
+
652
+ metric_dicts = []
653
+ for eval_result in eval_results:
654
+ metric_dict = eval_result.metric_vals_dict
655
+ metric_dicts.append(metric_dict)
656
+
657
+ full_df = pd.DataFrame(metric_dicts)
658
+
659
+ hit_rate = full_df["hit_rate"].mean()
660
+ mrr = full_df["mrr"].mean()
661
+
662
+ metric_df = pd.DataFrame(
663
+ {"Retriever Name": [name], "Hit Rate": [hit_rate], "MRR": [mrr]}
664
+ )
665
+
666
+ return metric_df
667
+
668
+
669
+ def display_results():
670
+
671
+ sources = [
672
+ "transformers",
673
+ "peft",
674
+ "trl",
675
+ "llama_index",
676
+ "langchain",
677
+ "openai_cookbooks",
678
+ "tai_blog",
679
+ ]
680
+ # retrievers_to_evaluate = [
681
+ # # "chroma-db-all_sources_400_0",
682
+ # # "chroma-db-all_sources_400_200",
683
+ # # "chroma-db-all_sources_500_0",
684
+ # # "chroma-db-all_sources_500_250",
685
+ # # "chroma-db-all_sources",
686
+ # # "chroma-db-all_sources_800_400",
687
+ # # "chroma-db-all_sources_1000_0",
688
+ # # "chroma-db-all_sources_1000_500",
689
+ # ]
690
+
691
+ # topk = [5, 7, 9, 11, 13, 15]
692
+ # for k in topk:
693
+ # for db_name in retrievers_to_evaluate:
694
+ if True:
695
+ # print("-" * 20)
696
+ # print(f"Retriever {db_name}")
697
+ for source in sources:
698
+ with open(f"eval_results_{source}.pkl", "rb") as f:
699
+ eval_results = pickle.load(f)
700
+ print(display_results_retriever(f"{source}", eval_results))
701
+
702
+
703
+ def display_results_answers():
704
+
705
+ sources = [
706
+ "transformers",
707
+ "peft",
708
+ "trl",
709
+ "llama_index",
710
+ "langchain",
711
+ "openai_cookbooks",
712
+ "tai_blog",
713
+ ]
714
+
715
+ for source in sources:
716
+ with open(f"eval_answers_results_{source}.pkl", "rb") as f:
717
+ eval_results = pickle.load(f)
718
+ print(
719
+ f"Score for {source}:",
720
+ sum(result.score for result in eval_results) / len(eval_results),
721
+ )
722
+
723
+
724
+ async def main():
725
+ await evaluate_retriever()
726
+ display_results()
727
+ # await evaluate_answers()
728
+ # display_results_answers()
729
+ return
730
+
731
+
732
+ if __name__ == "__main__":
733
+
734
+ logfire.configure()
735
+ rotating_writer = RotatingJSONLWriter(
736
+ "response_data.jsonl", max_size=10**7, backup_count=5
737
+ )
738
+
739
+ start_time = time.time()
740
+ asyncio.run(main())
741
+ end_time = time.time()
742
+ logfire.info(
743
+ f"Time taken to run script: {round((end_time - start_time), 3)} seconds"
744
+ )
745
+
746
+ # # Creating the keyword index and retriever
747
+ # logfire.info("Creating nodes from documents")
748
+ # documents = create_docs("data/all_sources_data.jsonl")
749
+ # pipeline = IngestionPipeline(
750
+ # transformations=[SentenceSplitter(chunk_size=800, chunk_overlap=0)]
751
+ # )
752
+ # all_nodes = pipeline.run(documents=documents, show_progress=True)
753
+ # # with open("data/all_nodes.pkl", "wb") as f:
754
+ # # pickle.dump(all_nodes, f)
755
+
756
+ # # all_nodes = pickle.load(open("data/all_nodes.pkl", "rb"))
757
+ # logfire.info(f"Number of nodes: {len(all_nodes)}")
758
+
759
+ # with open("processed_chunks.pkl", "rb") as f:
760
+ # all_nodes: list[TextNode] = pickle.load(f)
761
+
762
+ # keyword_index = SimpleKeywordTableIndex(
763
+ # nodes=all_nodes, max_keywords_per_chunk=10, show_progress=True, use_async=False
764
+ # )
765
+ # # with open("data/keyword_index.pkl", "wb") as f:
766
+ # # pickle.dump(keyword_index, f)
767
+ # # keyword_index = pickle.load(open("data/keyword_index.pkl", "rb"))
768
+
769
+ # logfire.info("Creating keyword retriever")
770
+ # keyword_retriever = AsyncKeywordTableSimpleRetriever(index=keyword_index)
771
+
772
+ # with open("data/keyword_retriever_async.pkl", "wb") as f:
773
+ # pickle.dump(keyword_retriever, f)
scripts/generate_qa_dataset.ipynb ADDED
@@ -0,0 +1,287 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "code",
5
+ "execution_count": null,
6
+ "metadata": {},
7
+ "outputs": [],
8
+ "source": [
9
+ "import nest_asyncio\n",
10
+ "\n",
11
+ "nest_asyncio.apply()"
12
+ ]
13
+ },
14
+ {
15
+ "cell_type": "markdown",
16
+ "metadata": {},
17
+ "source": [
18
+ "# Generate synthetic dataset of questions + doc ids\n"
19
+ ]
20
+ },
21
+ {
22
+ "cell_type": "code",
23
+ "execution_count": null,
24
+ "metadata": {},
25
+ "outputs": [],
26
+ "source": [
27
+ "# DEFAULT_QA_GENERATE_PROMPT_TMPL = \"\"\"\\\n",
28
+ "# Context information is below.\n",
29
+ "\n",
30
+ "# ---------------------\n",
31
+ "# {context_str}\n",
32
+ "# ---------------------\n",
33
+ "\n",
34
+ "# Given the context information and not prior knowledge.\n",
35
+ "# generate only questions based on the below query.\n",
36
+ "\n",
37
+ "# You are a Teacher/ Professor with expertise in the field of AI. Your task is to setup \\\n",
38
+ "# {num_questions_per_chunk} questions for an upcoming \\\n",
39
+ "# quiz/examination. The questions should be diverse in nature \\\n",
40
+ "# across the document. Restrict the questions to the \\\n",
41
+ "# context information provided.\"\n",
42
+ "# \"\"\"\n",
43
+ "\n",
44
+ "STUDENT_AI_QUESTIONS_GENERATE_PROMPT_TMPL = \"\"\"\\\n",
45
+ "Context information is below.\n",
46
+ "\n",
47
+ "---------------------\n",
48
+ "{context_str}\n",
49
+ "---------------------\n",
50
+ "\n",
51
+ "Given the context information above, generate {num_questions_per_chunk} questions that a student might ask about AI, specifically related to the information provided in the context, \n",
52
+ "but without the questions mentioning the context information.\n",
53
+ "\n",
54
+ "You are simulating curious students who are learning about AI. Your task is to create questions that:\n",
55
+ "1. Reflect genuine curiosity about the topics covered in the context.\n",
56
+ "2. Vary in complexity, from basic clarifications to more advanced inquiries.\n",
57
+ "3. Demonstrate a student's desire to understand AI concepts better.\n",
58
+ "4. Can be answered using the information provided in the context.\n",
59
+ "\n",
60
+ "The questions should be diverse and cover different aspects of the content. Do not use any prior knowledge beyond what's given in the context. Ensure that each question you generate can be answered using the information provided in the context.\n",
61
+ "\"\"\""
62
+ ]
63
+ },
64
+ {
65
+ "cell_type": "code",
66
+ "execution_count": null,
67
+ "metadata": {},
68
+ "outputs": [],
69
+ "source": [
70
+ "from llama_index.llms.openai import OpenAI\n",
71
+ "from llama_index.llms.gemini import Gemini\n",
72
+ "\n",
73
+ "# llm = Gemini(model=\"models/gemini-1.5-flash-latest\", temperature=1, max_tokens=1000)\n",
74
+ "llm = OpenAI(\n",
75
+ " api_key=\"\",\n",
76
+ " model=\"gpt-4o-mini\",\n",
77
+ " temperature=1,\n",
78
+ " max_tokens=1000,\n",
79
+ ")"
80
+ ]
81
+ },
82
+ {
83
+ "cell_type": "code",
84
+ "execution_count": null,
85
+ "metadata": {},
86
+ "outputs": [],
87
+ "source": [
88
+ "import json\n",
89
+ "import re\n",
90
+ "import uuid\n",
91
+ "import warnings\n",
92
+ "import asyncio\n",
93
+ "from typing import Dict, List, Tuple\n",
94
+ "\n",
95
+ "from llama_index.core.llms.llm import LLM\n",
96
+ "from llama_index.core.schema import MetadataMode, TextNode\n",
97
+ "from tqdm.asyncio import tqdm as async_tqdm\n",
98
+ "from llama_index.core.llama_dataset.legacy.embedding import EmbeddingQAFinetuneDataset\n",
99
+ "from llama_index.core import Document\n",
100
+ "\n",
101
+ "\n",
102
+ "async def generate_qa_embedding_pairs(\n",
103
+ " nodes: List[TextNode],\n",
104
+ " llm: LLM,\n",
105
+ " qa_generate_prompt_tmpl: str = STUDENT_AI_QUESTIONS_GENERATE_PROMPT_TMPL,\n",
106
+ " num_questions_per_chunk: int = 1,\n",
107
+ " max_concurrent: int = 10,\n",
108
+ " delay: float = 0.5,\n",
109
+ ") -> EmbeddingQAFinetuneDataset:\n",
110
+ " \"\"\"Generate examples given a set of nodes.\"\"\"\n",
111
+ " node_dict = {\n",
112
+ " node.node_id: node.get_content(metadata_mode=MetadataMode.NONE)\n",
113
+ " for node in nodes\n",
114
+ " }\n",
115
+ "\n",
116
+ " queries = {}\n",
117
+ " relevant_docs = {}\n",
118
+ " semaphore = asyncio.Semaphore(max_concurrent)\n",
119
+ "\n",
120
+ " async def process_node(node_id: str, text: str):\n",
121
+ " async with semaphore:\n",
122
+ " query = qa_generate_prompt_tmpl.format(\n",
123
+ " context_str=text, num_questions_per_chunk=num_questions_per_chunk\n",
124
+ " )\n",
125
+ " response = await llm.acomplete(\n",
126
+ " query\n",
127
+ " ) # Assuming the LLM has an async method\n",
128
+ "\n",
129
+ " result = str(response).strip().split(\"\\n\")\n",
130
+ " questions = [\n",
131
+ " re.sub(r\"^\\d+[\\).\\s]\", \"\", question).strip() for question in result\n",
132
+ " ]\n",
133
+ " questions = [question for question in questions if len(question) > 0][\n",
134
+ " :num_questions_per_chunk\n",
135
+ " ]\n",
136
+ "\n",
137
+ " num_questions_generated = len(questions)\n",
138
+ " if num_questions_generated < num_questions_per_chunk:\n",
139
+ " warnings.warn(\n",
140
+ " f\"Fewer questions generated ({num_questions_generated}) \"\n",
141
+ " f\"than requested ({num_questions_per_chunk}).\"\n",
142
+ " )\n",
143
+ "\n",
144
+ " for question in questions:\n",
145
+ " question_id = str(uuid.uuid4())\n",
146
+ " queries[question_id] = question\n",
147
+ " relevant_docs[question_id] = [node_id]\n",
148
+ "\n",
149
+ " await asyncio.sleep(delay)\n",
150
+ "\n",
151
+ " # Use asyncio.gather to process nodes concurrently\n",
152
+ " await async_tqdm.gather(\n",
153
+ " *[process_node(node_id, text) for node_id, text in node_dict.items()]\n",
154
+ " )\n",
155
+ "\n",
156
+ " # construct dataset\n",
157
+ " return EmbeddingQAFinetuneDataset(\n",
158
+ " queries=queries, corpus=node_dict, relevant_docs=relevant_docs\n",
159
+ " )"
160
+ ]
161
+ },
162
+ {
163
+ "cell_type": "code",
164
+ "execution_count": null,
165
+ "metadata": {},
166
+ "outputs": [],
167
+ "source": [
168
+ "import pickle\n",
169
+ "\n",
170
+ "\n",
171
+ "async def generate_questions(path, source_name):\n",
172
+ " nodes = []\n",
173
+ " with open(path, \"rb\") as f:\n",
174
+ " document_dict = pickle.load(f)\n",
175
+ " for doc_id in document_dict.keys():\n",
176
+ " doc: Document = document_dict[doc_id]\n",
177
+ " if doc.metadata[\"tokens\"] >= 100_000:\n",
178
+ " print(\"skipping\", doc.metadata[\"tokens\"])\n",
179
+ " continue\n",
180
+ " node = TextNode(text=doc.text, metadata=doc.metadata, id_=doc_id)\n",
181
+ " nodes.append(node)\n",
182
+ "\n",
183
+ " rag_eval_dataset: EmbeddingQAFinetuneDataset = await generate_qa_embedding_pairs(\n",
184
+ " nodes,\n",
185
+ " llm=llm,\n",
186
+ " num_questions_per_chunk=1,\n",
187
+ " qa_generate_prompt_tmpl=STUDENT_AI_QUESTIONS_GENERATE_PROMPT_TMPL,\n",
188
+ " max_concurrent=20, # Adjust this to control concurrency\n",
189
+ " delay=0.5, # Adjust this to add delay between API calls\n",
190
+ " )\n",
191
+ " rag_eval_dataset.save_json(f\"./rag_eval_{source_name}.json\")"
192
+ ]
193
+ },
194
+ {
195
+ "cell_type": "code",
196
+ "execution_count": null,
197
+ "metadata": {},
198
+ "outputs": [],
199
+ "source": [
200
+ "# await generate_questions(\n",
201
+ "# \"../data/chroma-db-langchain/document_dict_langchain.pkl\", \"langchain\"\n",
202
+ "# )\n",
203
+ "# await generate_questions(\n",
204
+ "# \"../data/chroma-db-llama_index/document_dict_llama_index.pkl\", \"llama_index\"\n",
205
+ "# )\n",
206
+ "# await generate_questions(\n",
207
+ "# \"../data/chroma-db-openai_cookbooks/document_dict_openai_cookbooks.pkl\",\n",
208
+ "# \"openai_cookbooks\",\n",
209
+ "# )\n",
210
+ "# await generate_questions(\"../data/chroma-db-peft/document_dict_peft.pkl\", \"peft\")\n",
211
+ "# await generate_questions(\"../data/chroma-db-trl/document_dict_trl.pkl\", \"trl\")\n",
212
+ "\n",
213
+ "await generate_questions(\n",
214
+ " \"../data/chroma-db-tai_blog/document_dict_tai_blog.pkl\", \"tai_blog\"\n",
215
+ ")"
216
+ ]
217
+ },
218
+ {
219
+ "cell_type": "code",
220
+ "execution_count": null,
221
+ "metadata": {},
222
+ "outputs": [],
223
+ "source": [
224
+ "# # We can also load the dataset from a previously saved json file.\n",
225
+ "# from llama_index.core.evaluation import EmbeddingQAFinetuneDataset\n",
226
+ "\n",
227
+ "# rag_eval_dataset = EmbeddingQAFinetuneDataset.from_json(\"./rag_eval_transformers.json\")"
228
+ ]
229
+ },
230
+ {
231
+ "cell_type": "code",
232
+ "execution_count": null,
233
+ "metadata": {},
234
+ "outputs": [],
235
+ "source": []
236
+ },
237
+ {
238
+ "cell_type": "code",
239
+ "execution_count": null,
240
+ "metadata": {},
241
+ "outputs": [],
242
+ "source": []
243
+ },
244
+ {
245
+ "cell_type": "code",
246
+ "execution_count": null,
247
+ "metadata": {},
248
+ "outputs": [],
249
+ "source": []
250
+ },
251
+ {
252
+ "cell_type": "code",
253
+ "execution_count": null,
254
+ "metadata": {},
255
+ "outputs": [],
256
+ "source": []
257
+ },
258
+ {
259
+ "cell_type": "code",
260
+ "execution_count": null,
261
+ "metadata": {},
262
+ "outputs": [],
263
+ "source": []
264
+ }
265
+ ],
266
+ "metadata": {
267
+ "kernelspec": {
268
+ "display_name": "env",
269
+ "language": "python",
270
+ "name": "python3"
271
+ },
272
+ "language_info": {
273
+ "codemirror_mode": {
274
+ "name": "ipython",
275
+ "version": 3
276
+ },
277
+ "file_extension": ".py",
278
+ "mimetype": "text/x-python",
279
+ "name": "python",
280
+ "nbconvert_exporter": "python",
281
+ "pygments_lexer": "ipython3",
282
+ "version": "3.12.5"
283
+ }
284
+ },
285
+ "nbformat": 4,
286
+ "nbformat_minor": 2
287
+ }
scripts/main.py ADDED
@@ -0,0 +1,268 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import pdb
2
+
3
+ import gradio as gr
4
+ import logfire
5
+ from custom_retriever import CustomRetriever
6
+ from llama_index.agent.openai import OpenAIAgent
7
+ from llama_index.core.llms import MessageRole
8
+ from llama_index.core.memory import ChatSummaryMemoryBuffer
9
+ from llama_index.core.tools import RetrieverTool, ToolMetadata
10
+ from llama_index.core.vector_stores import (
11
+ FilterCondition,
12
+ FilterOperator,
13
+ MetadataFilter,
14
+ MetadataFilters,
15
+ )
16
+ from llama_index.llms.openai import OpenAI
17
+ from prompts import system_message_openai_agent
18
+ from setup import (
19
+ AVAILABLE_SOURCES,
20
+ AVAILABLE_SOURCES_UI,
21
+ CONCURRENCY_COUNT,
22
+ custom_retriever_all_sources,
23
+ )
24
+
25
+
26
+ def update_query_engine_tools(selected_sources) -> list[RetrieverTool]:
27
+ tools = []
28
+ source_mapping: dict[str, tuple[CustomRetriever, str, str]] = {
29
+ "All Sources": (
30
+ custom_retriever_all_sources,
31
+ "all_sources_info",
32
+ """Useful tool that contains general information about the field of AI.""",
33
+ ),
34
+ }
35
+
36
+ for source in selected_sources:
37
+ if source in source_mapping:
38
+ custom_retriever, name, description = source_mapping[source]
39
+ tools.append(
40
+ RetrieverTool(
41
+ retriever=custom_retriever,
42
+ metadata=ToolMetadata(
43
+ name=name,
44
+ description=description,
45
+ ),
46
+ )
47
+ )
48
+
49
+ return tools
50
+
51
+
52
+ def generate_completion(
53
+ query,
54
+ history,
55
+ sources,
56
+ model,
57
+ memory,
58
+ ):
59
+ llm = OpenAI(temperature=1, model=model, max_tokens=None)
60
+ client = llm._get_client()
61
+ logfire.instrument_openai(client)
62
+
63
+ with logfire.span(f"Running query: {query}"):
64
+ logfire.info(f"User chosen sources: {sources}")
65
+
66
+ memory_chat_list = memory.get()
67
+
68
+ if len(memory_chat_list) != 0:
69
+ user_index_memory = [
70
+ i
71
+ for i, msg in enumerate(memory_chat_list)
72
+ if msg.role == MessageRole.USER
73
+ ]
74
+
75
+ user_index_history = [
76
+ i for i, msg in enumerate(history) if msg["role"] == "user"
77
+ ]
78
+
79
+ if len(user_index_memory) > len(user_index_history):
80
+ logfire.warn(f"There are more user messages in memory than in history")
81
+ user_index_to_remove = user_index_memory[len(user_index_history)]
82
+ memory_chat_list = memory_chat_list[:user_index_to_remove]
83
+ memory.set(memory_chat_list)
84
+
85
+ logfire.info(f"chat_history: {len(memory.get())} {memory.get()}")
86
+ logfire.info(f"gradio_history: {len(history)} {history}")
87
+
88
+ query_engine_tools: list[RetrieverTool] = update_query_engine_tools(
89
+ ["All Sources"]
90
+ )
91
+
92
+ filter_list = []
93
+ source_mapping = {
94
+ "Transformers Docs": "transformers",
95
+ "PEFT Docs": "peft",
96
+ "TRL Docs": "trl",
97
+ "LlamaIndex Docs": "llama_index",
98
+ "LangChain Docs": "langchain",
99
+ "OpenAI Cookbooks": "openai_cookbooks",
100
+ "Towards AI Blog": "tai_blog",
101
+ "8 Hour Primer": "8-hour_primer",
102
+ "Advanced LLM Developer": "llm_developer",
103
+ "Python Primer": "python_primer",
104
+ }
105
+
106
+ for source in sources:
107
+ if source in source_mapping:
108
+ filter_list.append(
109
+ MetadataFilter(
110
+ key="source",
111
+ operator=FilterOperator.EQ,
112
+ value=source_mapping[source],
113
+ )
114
+ )
115
+
116
+ filters = MetadataFilters(
117
+ filters=filter_list,
118
+ condition=FilterCondition.OR,
119
+ )
120
+ logfire.info(f"Filters: {filters}")
121
+ query_engine_tools[0].retriever._vector_retriever._filters = filters
122
+
123
+ # pdb.set_trace()
124
+
125
+ agent = OpenAIAgent.from_tools(
126
+ llm=llm,
127
+ memory=memory,
128
+ tools=query_engine_tools,
129
+ system_prompt=system_message_openai_agent,
130
+ )
131
+
132
+ completion = agent.stream_chat(query)
133
+
134
+ answer_str = ""
135
+ for token in completion.response_gen:
136
+ answer_str += token
137
+ yield answer_str
138
+
139
+ for answer_str in add_sources(answer_str, completion):
140
+ yield answer_str
141
+
142
+
143
+ def add_sources(answer_str, completion):
144
+ if completion is None:
145
+ yield answer_str
146
+
147
+ formatted_sources = format_sources(completion)
148
+ if formatted_sources == "":
149
+ yield answer_str
150
+
151
+ if formatted_sources != "":
152
+ answer_str += "\n\n" + formatted_sources
153
+
154
+ yield answer_str
155
+
156
+
157
+ def format_sources(completion) -> str:
158
+ if len(completion.sources) == 0:
159
+ return ""
160
+
161
+ # logfire.info(f"Formatting sources: {completion.sources}")
162
+
163
+ display_source_to_ui = {
164
+ src: ui for src, ui in zip(AVAILABLE_SOURCES, AVAILABLE_SOURCES_UI)
165
+ }
166
+
167
+ documents_answer_template: str = (
168
+ "📝 Here are the sources I used to answer your question:\n{documents}"
169
+ )
170
+ document_template: str = "[🔗 {source}: {title}]({url}), relevance: {score:2.2f}"
171
+ all_documents = []
172
+ for source in completion.sources: # looping over list[ToolOutput]
173
+ if isinstance(source.raw_output, Exception):
174
+ logfire.error(f"Error in source output: {source.raw_output}")
175
+ # pdb.set_trace()
176
+ continue
177
+
178
+ if not isinstance(source.raw_output, list):
179
+ logfire.warn(f"Unexpected source output type: {type(source.raw_output)}")
180
+ continue
181
+ for src in source.raw_output: # looping over list[NodeWithScore]
182
+ document = document_template.format(
183
+ title=src.metadata["title"],
184
+ score=src.score,
185
+ source=display_source_to_ui.get(
186
+ src.metadata["source"], src.metadata["source"]
187
+ ),
188
+ url=src.metadata["url"],
189
+ )
190
+ all_documents.append(document)
191
+
192
+ if len(all_documents) == 0:
193
+ return ""
194
+ else:
195
+ documents = "\n".join(all_documents)
196
+ return documents_answer_template.format(documents=documents)
197
+
198
+
199
+ def save_completion(completion, history):
200
+ pass
201
+
202
+
203
+ def vote(data: gr.LikeData):
204
+ pass
205
+
206
+
207
+ accordion = gr.Accordion(label="Customize Sources (Click to expand)", open=False)
208
+ sources = gr.CheckboxGroup(
209
+ AVAILABLE_SOURCES_UI,
210
+ label="Sources",
211
+ value=[
212
+ "Advanced LLM Developer",
213
+ "8 Hour Primer",
214
+ "Python Primer",
215
+ "Towards AI Blog",
216
+ "Transformers Docs",
217
+ "PEFT Docs",
218
+ "TRL Docs",
219
+ "LlamaIndex Docs",
220
+ "LangChain Docs",
221
+ "OpenAI Cookbooks",
222
+ ],
223
+ interactive=True,
224
+ )
225
+ model = gr.Dropdown(
226
+ [
227
+ "gpt-4o-mini",
228
+ #Kenny added GPT2
229
+ #"gpt2",
230
+ ],
231
+ label="Model",
232
+ value="gpt-4o-mini",
233
+ interactive=False,
234
+ )
235
+
236
+ with gr.Blocks(
237
+ title="Towards AI 🤖",
238
+ analytics_enabled=True,
239
+ fill_height=True,
240
+ ) as demo:
241
+
242
+ memory = gr.State(
243
+ lambda: ChatSummaryMemoryBuffer.from_defaults(
244
+ token_limit=120000,
245
+ )
246
+ )
247
+ chatbot = gr.Chatbot(
248
+ type="messages",
249
+ scale=20,
250
+ placeholder="<strong>Towards AI 🤖: A Question-Answering Bot for anything AI-related</strong><br>",
251
+ show_label=False,
252
+ show_copy_button=True,
253
+ )
254
+ chatbot.like(vote, None, None)
255
+ gr.ChatInterface(
256
+ fn=generate_completion,
257
+ type="messages",
258
+ chatbot=chatbot,
259
+ additional_inputs=[sources, model, memory],
260
+ additional_inputs_accordion=accordion,
261
+ # fill_height=True,
262
+ # fill_width=True,
263
+ analytics_enabled=True,
264
+ )
265
+
266
+ if __name__ == "__main__":
267
+ demo.queue(default_concurrency_limit=CONCURRENCY_COUNT)
268
+ demo.launch(debug=False, share=False)
scripts/prompts.py ADDED
@@ -0,0 +1,29 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Prompt 5
2
+ system_message_openai_agent = """You are an AI teacher, answering questions from students of an applied AI course on Large Language Models (LLMs or llm), Retrieval Augmented Generation (RAG) for LLMs and Python programming (computer science in general).
3
+
4
+ Topics covered include coding with Python, training models, fine-tuning models, giving memory to LLMs, prompting tips, hallucinations and bias, vector databases, transformer architectures, embeddings, RAG frameworks such as Langchain and LlamaIndex, making LLMs interact with tools, AI agents, reinforcement learning with human feedback (RLHF). Questions should be understood in this context.
5
+
6
+ Your answers are aimed to teach students, so they should be complete, clear, and easy to understand.
7
+
8
+ Use the available tools to gather insights pertinent to the field of AI.
9
+
10
+ To answer student questions, always use the all_sources_info tool.
11
+
12
+ Only some information returned by the tools might be relevant to the question, so ignore the irrelevant part and answer the question with what you have.
13
+
14
+ Your responses are exclusively based on the output provided by the tools. Refrain from incorporating information not directly obtained from the tool's responses.
15
+
16
+ When the conversation deepens or shifts focus within a topic, adapt your input to the tools to reflect these nuances. This means if a user requests further elaboration on a specific aspect of a previously discussed topic, you should reformulate your input to the tool to capture this new angle or more profound layer of inquiry.
17
+
18
+ Provide comprehensive answers, ideally structured in multiple paragraphs, drawing from the tool's variety of relevant details. The depth and breadth of your responses should align with the scope and specificity of the information retrieved.
19
+
20
+ Should the tools repository lack information on the queried topic, politely inform the user that the question transcends the bounds of your current knowledge base, citing the absence of relevant content in the tool's documentation.
21
+
22
+ At the end of your answers, always invite the students to ask deeper questions about the topic if they have any. Make sure reformulate the question to the tool to capture this new angle or more profound layer of inquiry.
23
+
24
+ Do not refer to the documentation directly, but use the information provided within it to answer questions.
25
+
26
+ If code is provided in the information, share it with the students. It's important to provide complete code blocks so they can execute the code when they copy and paste them.
27
+
28
+ Make sure to format your answers in Markdown format, including code blocks and snippets.
29
+ """
scripts/setup.py ADDED
@@ -0,0 +1,146 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import asyncio
2
+ import json
3
+ import logging
4
+ import os
5
+ import pickle
6
+
7
+ import chromadb
8
+ import logfire
9
+ from custom_retriever import CustomRetriever
10
+ from dotenv import load_dotenv
11
+ from llama_index.core import Document, VectorStoreIndex
12
+ from llama_index.core.node_parser import SentenceSplitter
13
+ from llama_index.core.retrievers import VectorIndexRetriever
14
+ from llama_index.embeddings.cohere import CohereEmbedding
15
+ from llama_index.vector_stores.chroma import ChromaVectorStore
16
+ from utils import init_mongo_db
17
+
18
+ load_dotenv()
19
+
20
+ logfire.configure()
21
+
22
+ if not os.path.exists("data/chroma-db-all_sources"):
23
+ # Download the vector database from the Hugging Face Hub if it doesn't exist locally
24
+ # https://huggingface.co/datasets/towardsai-buster/ai-tutor-vector-db/tree/main
25
+ logfire.warn(
26
+ f"Vector database does not exist at 'data/chroma-db-all_sources', downloading from Hugging Face Hub"
27
+ )
28
+ from huggingface_hub import snapshot_download
29
+
30
+ snapshot_download(
31
+ repo_id="towardsai-tutors/ai-tutor-vector-db",
32
+ local_dir="data",
33
+ repo_type="dataset",
34
+ )
35
+ logfire.info(f"Downloaded vector database to 'data/chroma-db-all_sources'")
36
+
37
+
38
+ def create_docs(input_file: str) -> list[Document]:
39
+ with open(input_file, "r") as f:
40
+ documents = []
41
+ for line in f:
42
+ data = json.loads(line)
43
+ documents.append(
44
+ Document(
45
+ doc_id=data["doc_id"],
46
+ text=data["content"],
47
+ metadata={ # type: ignore
48
+ "url": data["url"],
49
+ "title": data["name"],
50
+ "tokens": data["tokens"],
51
+ "retrieve_doc": data["retrieve_doc"],
52
+ "source": data["source"],
53
+ },
54
+ excluded_llm_metadata_keys=[
55
+ "title",
56
+ "tokens",
57
+ "retrieve_doc",
58
+ "source",
59
+ ],
60
+ excluded_embed_metadata_keys=[
61
+ "url",
62
+ "tokens",
63
+ "retrieve_doc",
64
+ "source",
65
+ ],
66
+ )
67
+ )
68
+ return documents
69
+
70
+
71
+ def setup_database(db_collection, dict_file_name) -> CustomRetriever:
72
+ db = chromadb.PersistentClient(path=f"data/{db_collection}")
73
+ chroma_collection = db.get_or_create_collection(db_collection)
74
+ vector_store = ChromaVectorStore(chroma_collection=chroma_collection)
75
+ embed_model = CohereEmbedding(
76
+ api_key=os.environ["COHERE_API_KEY"],
77
+ model_name="embed-english-v3.0",
78
+ input_type="search_query",
79
+ )
80
+
81
+ index = VectorStoreIndex.from_vector_store(
82
+ vector_store=vector_store,
83
+ transformations=[SentenceSplitter(chunk_size=800, chunk_overlap=0)],
84
+ show_progress=True,
85
+ # use_async=True,
86
+ )
87
+ vector_retriever = VectorIndexRetriever(
88
+ index=index,
89
+ similarity_top_k=15,
90
+ embed_model=embed_model,
91
+ # use_async=True,
92
+ )
93
+ with open(f"data/{db_collection}/{dict_file_name}", "rb") as f:
94
+ document_dict = pickle.load(f)
95
+
96
+ return CustomRetriever(vector_retriever, document_dict)
97
+
98
+
99
+ custom_retriever_all_sources: CustomRetriever = setup_database(
100
+ "chroma-db-all_sources",
101
+ "document_dict_all_sources.pkl",
102
+ )
103
+
104
+
105
+ CONCURRENCY_COUNT = int(os.getenv("CONCURRENCY_COUNT", 64))
106
+ MONGODB_URI = os.getenv("MONGODB_URI")
107
+
108
+ AVAILABLE_SOURCES_UI = [
109
+ "Transformers Docs",
110
+ "PEFT Docs",
111
+ "TRL Docs",
112
+ "LlamaIndex Docs",
113
+ "LangChain Docs",
114
+ "OpenAI Cookbooks",
115
+ "Towards AI Blog",
116
+ "8 Hour Primer",
117
+ "Advanced LLM Developer",
118
+ "Python Primer",
119
+ ]
120
+
121
+ AVAILABLE_SOURCES = [
122
+ "transformers",
123
+ "peft",
124
+ "trl",
125
+ "llama_index",
126
+ "langchain",
127
+ "openai_cookbooks",
128
+ "tai_blog",
129
+ "8-hour_primer",
130
+ "llm_developer",
131
+ "python_primer",
132
+ ]
133
+
134
+ mongo_db = (
135
+ init_mongo_db(uri=MONGODB_URI, db_name="towardsai-buster")
136
+ if MONGODB_URI
137
+ else logfire.warn("No mongodb uri found, you will not be able to save data.")
138
+ )
139
+
140
+ __all__ = [
141
+ "custom_retriever_all_sources",
142
+ "mongo_db",
143
+ "CONCURRENCY_COUNT",
144
+ "AVAILABLE_SOURCES_UI",
145
+ "AVAILABLE_SOURCES",
146
+ ]
scripts/utils.py ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from pymongo.mongo_client import MongoClient
2
+ from pymongo.server_api import ServerApi
3
+
4
+
5
+ def init_mongo_db(uri: str, db_name: str):
6
+ """Initialize the mongodb database."""
7
+
8
+ try:
9
+ assert uri is not None, "No URI passed"
10
+ client = MongoClient(uri, server_api=ServerApi("1"))
11
+ database = client[db_name]
12
+ print("Connected to MongoDB")
13
+ return database
14
+ except Exception as e:
15
+ print("Something went wrong connecting to mongodb")
16
+ return