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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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 |
+
}
|