| 27 | AppConfig.initialize_environment_variables() |
| 28 | |
| 29 | def generate_questions(self,llm, parent_documents, documentId, embeddings, driver): |
| 30 | |
| 31 | # Generate Questions for page node |
| 32 | logging.info(f"Generating questions for document {documentId}") |
| 33 | questions_prompt = ChatPromptTemplate.from_messages( |
| 34 | [ |
| 35 | ( |
| 36 | "system", |
| 37 | ( |
| 38 | "You are generating hypothetical questions based on the information " |
| 39 | "found in the text. Make sure to provide full context in the generated " |
| 40 | "questions." |
| 41 | ), |
| 42 | ), |
| 43 | ( |
| 44 | "human", |
| 45 | ( |
| 46 | "Use the given format to generate hypothetical questions from the " |
| 47 | "following input: {input}" |
| 48 | ), |
| 49 | ), |
| 50 | ] |
| 51 | ) |
| 52 | |
| 53 | logging.info(f"LLM type: {type(llm)}, Prompt: {questions_prompt}") |
| 54 | |
| 55 | question_chain = create_structured_output_chain(Questions, llm, questions_prompt) |
| 56 | |
| 57 | for i, parent in enumerate(parent_documents): |
| 58 | self.update_state(state=AppConfig.PROCESSING_QUESTIONS, meta={"page": i+1, "total_pages": len(parent_documents), "documentId": documentId}) |
| 59 | logging.info(f"Generating questions for page {i+1} of {len(parent_documents)} for document {documentId}") |
| 60 | generated_questions = question_chain.run(parent.page_content).questions |
| 61 | limited_questions = generated_questions[:AppConfig.MAX_QUESTIONS_PER_PAGE] # Limit the number of questions |
| 62 | |
| 63 | params = { |
| 64 | "parent_id": f"Page {i+1}", |
| 65 | "document_uuid": documentId, |
| 66 | "questions": [ |
| 67 | { |
| 68 | "text": q, |
| 69 | "uuid": str(uuid.uuid4()), |
| 70 | "name": f"{i+1}-{iq+1}", |
| 71 | "embedding": embeddings.embed_query(q) |
| 72 | } |
| 73 | for iq, q in enumerate(limited_questions) if q # Iterate over limited questions |
| 74 | ], |
| 75 | } |
| 76 | with driver.session() as session : |
| 77 | session.run( |
| 78 | """ |
| 79 | match (d:Document)-[]-(p:Page) where d.uuid=$document_uuid and p.name=$parent_id |
| 80 | WITH p |
| 81 | UNWIND $questions AS question |
| 82 | CREATE (q:Question {uuid: question.uuid}) |
| 83 | SET q.text = question.text, q.name = question.name, q.datecreated= datetime(), q.source=p.uuid |
| 84 | MERGE (q)<-[:HAS_QUESTION]-(p) |
| 85 | WITH q, question |
| 86 | CALL db.create.setVectorProperty(q, 'embedding', question.embedding) |