RaghuCourage9605 commited on
Commit
19557c6
·
verified ·
1 Parent(s): 3222b08

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +137 -128
app.py CHANGED
@@ -1,132 +1,141 @@
1
- import gradio as gr
2
- from langchain_community.chat_message_histories import Neo4jChatMessageHistory
3
- from langchain_core.runnables.history import RunnableWithMessageHistory
4
- from langchain.prompts import ChatPromptTemplate
5
- from langchain.schema import StrOutputParser
6
- from langchain_huggingface import HuggingFaceEmbeddings
7
- from langchain_core.prompts.chat import MessagesPlaceholder
8
- from langchain_community.vectorstores import Neo4jVector
9
- from langchain_neo4j import Neo4jGraph
10
- from langchain_google_genai import ChatGoogleGenerativeAI
11
- from uuid import uuid4
12
- import os
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
13
  from dotenv import load_dotenv
14
- import asyncio
15
 
16
- # Load environment variables
17
  load_dotenv()
18
 
19
- # Initialize variables
20
- SESSION_ID = str(uuid4())
21
- print(f"Session ID: {SESSION_ID}")
22
-
23
- # Neo4j graph setup
24
- graph = Neo4jGraph(
25
- url="neo4j+s://6682e6ce.databases.neo4j.io",
26
- username="neo4j",
27
- password=os.getenv("NEO4J_PASSWORD")
28
- )
29
-
30
- # HuggingFace embeddings
31
- embeddings = HuggingFaceEmbeddings(
32
- model_name="sentence-transformers/all-MiniLM-L6-v2",
33
- model_kwargs={'device': 'cpu'},
34
- encode_kwargs={'normalize_embeddings': False}
35
- )
36
-
37
- # Create Neo4j VectorStore
38
- graph_store = Neo4jVector.from_existing_index(
39
- embeddings,
40
- graph=graph,
41
- index_name="vector",
42
- embedding_node_property="Embedding",
43
- text_node_property="text",
44
- retrieval_query="""
45
- // get the document
46
- MATCH (node)-[:PART_OF]->(d:Document)
47
- WITH node, score, d
48
-
49
- // get the entities and relationships for the document
50
- MATCH (node)-[:HAS_ENTITY]->(e)
51
- MATCH p = (e)-[r]-(e2)
52
- WHERE (node)-[:HAS_ENTITY]->(e2)
53
-
54
- // unwind the path, create a string of the entities and relationships
55
- UNWIND relationships(p) as rels
56
- WITH
57
- node,
58
- score,
59
- d,
60
- collect(apoc.text.join(
61
- [labels(startNode(rels))[0], startNode(rels).id, type(rels), labels(endNode(rels))[0], endNode(rels).id]
62
- ," ")) as kg
63
- RETURN
64
- node.text as text, score,
65
- {
66
- document: d.id,
67
- entities: kg
68
- } AS metadata
69
- """)
70
- retriever = graph_store.as_retriever()
71
-
72
- # Define Cypher Prompt
73
- CYPHER_PROMPT = """
74
- (
75
- "Use the given context to provide an in-depth and structured response."
76
- "Your answer should include:"
77
- "- A clear and concise introduction to the topic."
78
- "- Detailed explanation or relevant steps to address the query."
79
- "- Practical examples or applications where possible."
80
- "- A conclusion summarizing the main points."
81
- "Format your response in sections with appropriate headings for clarity."
82
- "Context: {context}"
83
- )
84
- """
85
- prompt = ChatPromptTemplate.from_messages([
86
- ("system", CYPHER_PROMPT),
87
- MessagesPlaceholder(variable_name="chat_history"),
88
- ("human", "{question}")
89
- ])
90
-
91
- # Helper function to retrieve context
92
- def get_retrieved_context(query: str) -> str:
93
- retrieved_documents = retriever.get_relevant_documents(query)
94
- context = "\n".join(doc.page_content for doc in retrieved_documents)
95
- return context
96
-
97
- def get_memory(session_id):
98
- return Neo4jChatMessageHistory(session_id=session_id, graph=graph)
99
-
100
- def ReturnResponse(query: str) -> str:
101
- llm = ChatGoogleGenerativeAI(
102
- model='gemini-2.0-flash-exp',
103
- api_key=os.getenv("GOOGLE_AI_STUDIO_API_KEY")
104
- )
105
- chat_chain = prompt | llm | StrOutputParser()
106
-
107
- chat_with_message_history = RunnableWithMessageHistory(
108
- chat_chain,
109
- get_memory,
110
- input_messages_key="question",
111
- history_messages_key="chat_history",
112
- )
113
-
114
- context = get_retrieved_context(query)
115
- response = chat_with_message_history.invoke({
116
- "question": query,
117
- "context": context,
118
- }, config={
119
- "configurable": {"session_id": SESSION_ID}
120
- })
121
-
122
- return gr.Markdown(response)
123
-
124
-
125
- iface = gr.Interface(
126
- fn=ReturnResponse,
127
- inputs=gr.Textbox(label="Enter your query:", placeholder="Type your question here..."),
128
- outputs=gr.Markdown(label="Chatbot Response"),
129
- title="GraphRAG with conversational Memory 🤖💬"
130
- )
131
-
132
- iface.launch()
 
1
+ # import gradio as gr
2
+ # from langchain_community.chat_message_histories import Neo4jChatMessageHistory
3
+ # from langchain_core.runnables.history import RunnableWithMessageHistory
4
+ # from langchain.prompts import ChatPromptTemplate
5
+ # from langchain.schema import StrOutputParser
6
+ # from langchain_huggingface import HuggingFaceEmbeddings
7
+ # from langchain_core.prompts.chat import MessagesPlaceholder
8
+ # from langchain_community.vectorstores import Neo4jVector
9
+ # from langchain_neo4j import Neo4jGraph
10
+ # from langchain_google_genai import ChatGoogleGenerativeAI
11
+ # from uuid import uuid4
12
+ # import os
13
+ # from dotenv import load_dotenv
14
+ # import asyncio
15
+
16
+ # # Load environment variables
17
+ # load_dotenv()
18
+
19
+ # # Initialize variables
20
+ # SESSION_ID = str(uuid4())
21
+ # print(f"Session ID: {SESSION_ID}")
22
+
23
+ # # Neo4j graph setup
24
+ # graph = Neo4jGraph(
25
+ # url="neo4j+s://6682e6ce.databases.neo4j.io",
26
+ # username="neo4j",
27
+ # password=os.getenv("NEO4J_PASSWORD")
28
+ # )
29
+
30
+ # # HuggingFace embeddings
31
+ # embeddings = HuggingFaceEmbeddings(
32
+ # model_name="sentence-transformers/all-MiniLM-L6-v2",
33
+ # model_kwargs={'device': 'cpu'},
34
+ # encode_kwargs={'normalize_embeddings': False}
35
+ # )
36
+
37
+ # # Create Neo4j VectorStore
38
+ # graph_store = Neo4jVector.from_existing_index(
39
+ # embeddings,
40
+ # graph=graph,
41
+ # index_name="vector",
42
+ # embedding_node_property="Embedding",
43
+ # text_node_property="text",
44
+ # retrieval_query="""
45
+ # // get the document
46
+ # MATCH (node)-[:PART_OF]->(d:Document)
47
+ # WITH node, score, d
48
+
49
+ # // get the entities and relationships for the document
50
+ # MATCH (node)-[:HAS_ENTITY]->(e)
51
+ # MATCH p = (e)-[r]-(e2)
52
+ # WHERE (node)-[:HAS_ENTITY]->(e2)
53
+
54
+ # // unwind the path, create a string of the entities and relationships
55
+ # UNWIND relationships(p) as rels
56
+ # WITH
57
+ # node,
58
+ # score,
59
+ # d,
60
+ # collect(apoc.text.join(
61
+ # [labels(startNode(rels))[0], startNode(rels).id, type(rels), labels(endNode(rels))[0], endNode(rels).id]
62
+ # ," ")) as kg
63
+ # RETURN
64
+ # node.text as text, score,
65
+ # {
66
+ # document: d.id,
67
+ # entities: kg
68
+ # } AS metadata
69
+ # """)
70
+ # retriever = graph_store.as_retriever()
71
+
72
+ # # Define Cypher Prompt
73
+ # CYPHER_PROMPT = """
74
+ # (
75
+ # "Use the given context to provide an in-depth and structured response."
76
+ # "Your answer should include:"
77
+ # "- A clear and concise introduction to the topic."
78
+ # "- Detailed explanation or relevant steps to address the query."
79
+ # "- Practical examples or applications where possible."
80
+ # "- A conclusion summarizing the main points."
81
+ # "Format your response in sections with appropriate headings for clarity."
82
+ # "Context: {context}"
83
+ # )
84
+ # """
85
+ # prompt = ChatPromptTemplate.from_messages([
86
+ # ("system", CYPHER_PROMPT),
87
+ # MessagesPlaceholder(variable_name="chat_history"),
88
+ # ("human", "{question}")
89
+ # ])
90
+
91
+ # # Helper function to retrieve context
92
+ # def get_retrieved_context(query: str) -> str:
93
+ # retrieved_documents = retriever.get_relevant_documents(query)
94
+ # context = "\n".join(doc.page_content for doc in retrieved_documents)
95
+ # return context
96
+
97
+ # def get_memory(session_id):
98
+ # return Neo4jChatMessageHistory(session_id=session_id, graph=graph)
99
+
100
+ # def ReturnResponse(query: str) -> str:
101
+ # llm = ChatGoogleGenerativeAI(
102
+ # model='gemini-2.0-flash-exp',
103
+ # api_key=os.getenv("GOOGLE_AI_STUDIO_API_KEY")
104
+ # )
105
+ # chat_chain = prompt | llm | StrOutputParser()
106
+
107
+ # chat_with_message_history = RunnableWithMessageHistory(
108
+ # chat_chain,
109
+ # get_memory,
110
+ # input_messages_key="question",
111
+ # history_messages_key="chat_history",
112
+ # )
113
+
114
+ # context = get_retrieved_context(query)
115
+ # response = chat_with_message_history.invoke({
116
+ # "question": query,
117
+ # "context": context,
118
+ # }, config={
119
+ # "configurable": {"session_id": SESSION_ID}
120
+ # })
121
+
122
+ # return gr.Markdown(response)
123
+
124
+
125
+ # iface = gr.Interface(
126
+ # fn=ReturnResponse,
127
+ # inputs=gr.Textbox(label="Enter your query:", placeholder="Type your question here..."),
128
+ # outputs=gr.Markdown(label="Chatbot Response"),
129
+ # title="GraphRAG with conversational Memory 🤖💬"
130
+ # )
131
+
132
+ # iface.launch()
133
  from dotenv import load_dotenv
134
+ import os
135
 
136
+ # Load the environment variables from .env file
137
  load_dotenv()
138
 
139
+ # Now you can access your secrets
140
+ neo4j_password = os.getenv("NEO4J_PASSWORD")
141
+ print(neo4j_password)