Skip to content

Backend connection config #1060

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 16 commits into from
Feb 11, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
124 changes: 66 additions & 58 deletions backend/score.py

Large diffs are not rendered by default.

9 changes: 7 additions & 2 deletions backend/src/graph_query.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,11 @@ def get_graphDB_driver(uri, username, password,database="neo4j"):
"""
try:
logging.info(f"Attempting to connect to the Neo4j database at {uri}")
if all(v is None for v in [username, password]):
username= os.getenv('NEO4J_USERNAME')
database= os.getenv('NEO4J_DATABASE')
password= os.getenv('NEO4J_PASSWORD')

enable_user_agent = os.environ.get("ENABLE_USER_AGENT", "False").lower() in ("true", "1", "yes")
if enable_user_agent:
driver = GraphDatabase.driver(uri, auth=(username, password),database=database, user_agent=os.environ.get('NEO4J_USER_AGENT'))
Expand Down Expand Up @@ -229,7 +234,7 @@ def get_chunktext_results(uri, username, password, database, document_name, page
offset = 10
skip = (page_no - 1) * offset
limit = offset
driver = GraphDatabase.driver(uri, auth=(username, password))
driver = get_graphDB_driver(uri, username, password,database)
with driver.session(database=database) as session:
total_chunks_result = session.run(COUNT_CHUNKS_QUERY, file_name=document_name)
total_chunks = total_chunks_result.single()["total_chunks"]
Expand Down Expand Up @@ -261,7 +266,7 @@ def visualize_schema(uri, userName, password, database):
driver = None
try:
logging.info("Starting visualizing graph schema")
driver = GraphDatabase.driver(uri, auth=(userName, password),database=database)
driver = get_graphDB_driver(uri, userName, password,database)
records, summary, keys = driver.execute_query(SCHEMA_VISUALIZATION_QUERY)
nodes = records[0].get("nodes", [])
relationships = records[0].get("relationships", [])
Expand Down
10 changes: 5 additions & 5 deletions frontend/src/API/Index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,11 +9,11 @@ const api = axios.create({

export const createDefaultFormData = (userCredentials: UserCredentials) => {
const formData = new FormData();
formData.append('uri', userCredentials?.uri ?? '');
formData.append('database', userCredentials?.database ?? '');
formData.append('userName', userCredentials?.userName ?? '');
formData.append('password', userCredentials?.password ?? '');
formData.append('email', userCredentials?.email ?? '');
if (userCredentials?.uri) formData.append('uri', userCredentials?.uri);
if (userCredentials?.database) formData.append('database', userCredentials?.database);
if (userCredentials?.userName) formData.append('userName', userCredentials?.userName);
if (userCredentials?.password) formData.append('password', userCredentials?.password);
if (userCredentials?.email) formData.append('email', userCredentials?.email);
api.interceptors.request.use(
(config) => {
if (config.data instanceof FormData) {
Expand Down
29 changes: 16 additions & 13 deletions frontend/src/components/ChatBot/ChatInfoModal.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -82,12 +82,11 @@ const ChatInfoModal: React.FC<chatInfoMessage> = ({
error?.length
? 10
: mode === chatModeLables['global search+vector+fulltext']
? 7
: mode === chatModeLables.graph
? 4
: 3
? 7
: mode === chatModeLables.graph
? 4
: 3
);
const { userCredentials } = useCredentials();
const [, copy] = useCopyToClipboard();
const [copiedText, setcopiedText] = useState<boolean>(false);
const [showMetricsTable, setShowMetricsTable] = useState<boolean>(Boolean(metricDetails));
Expand All @@ -99,15 +98,15 @@ const ChatInfoModal: React.FC<chatInfoMessage> = ({
multiModelMetrics.length > 0 && Object.keys(multiModelMetrics[0]).length > 4
? true
: multiModelMetrics.length > 0 && Object.keys(multiModelMetrics[0]).length <= 4
? false
: null
? false
: null
);
const [isAdditionalMetricsWithSingleMode, setIsAdditionalMetricsWithSingleMode] = useState<boolean | null>(
metricDetails != undefined && Object.keys(metricDetails).length > 3
? true
: metricDetails != undefined && Object.keys(metricDetails).length <= 3
? false
: null
? false
: null
);

const actions: React.ComponentProps<typeof IconButton<'button'>>[] = useMemo(
Expand Down Expand Up @@ -141,7 +140,11 @@ const ChatInfoModal: React.FC<chatInfoMessage> = ({
(async () => {
toggleInfoLoading();
try {
const response = await chunkEntitiesAPI(userCredentials?.database, nodeDetails, entities_ids, mode);
const response = await chunkEntitiesAPI(
nodeDetails,
entities_ids,
mode,
);
if (response.data.status === 'Failure') {
throw new Error(response.data.error);
}
Expand Down Expand Up @@ -350,9 +353,9 @@ const ChatInfoModal: React.FC<chatInfoMessage> = ({
{mode != chatModeLables.graph ? <Tabs.Tab tabId={3}>Sources used</Tabs.Tab> : <></>}
{mode != chatModeLables.graph ? <Tabs.Tab tabId={5}>Chunks</Tabs.Tab> : <></>}
{mode === chatModeLables['graph+vector'] ||
mode === chatModeLables.graph ||
mode === chatModeLables['graph+vector+fulltext'] ||
mode === chatModeLables['entity search+vector'] ? (
mode === chatModeLables.graph ||
mode === chatModeLables['graph+vector+fulltext'] ||
mode === chatModeLables['entity search+vector'] ? (
<Tabs.Tab tabId={4}>Top Entities used</Tabs.Tab>
) : (
<></>
Expand Down
16 changes: 12 additions & 4 deletions frontend/src/components/ChatBot/ChatOnlyComponent.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -34,9 +34,17 @@ const ChatContent: React.FC<ChatProps> = ({ chatMessages }) => {
const port = urlParams.get('port');
const email = urlParams.get('email');
const openModal = urlParams.get('open') === 'true';
const connectionStatus = urlParams.get('connectionStatus') === 'true';
if (openModal || !(uri && user && encodedPassword && database && port)) {
setOpenConnection((prev) => ({ ...prev, openPopUp: true }));
} else {
if (connectionStatus) {
setShowBackButton();
setConnectionStatus(connectionStatus);
setMessages(chatMessages);
} else {
setOpenConnection((prev) => ({ ...prev, openPopUp: true }));
}
}
else {
const credentialsForAPI: UserCredentials = {
uri,
userName: user,
Expand Down Expand Up @@ -75,9 +83,9 @@ const ChatContent: React.FC<ChatProps> = ({ chatMessages }) => {
try {
setClearHistoryData(true);
setIsDeleteChatLoading(true);
const credentials = JSON.parse(localStorage.getItem('neo4j.connection') || '{}') as UserCredentials;
// const credentials = JSON.parse(localStorage.getItem('neo4j.connection') || '{}') as UserCredentials;
const sessionId = sessionStorage.getItem('session_id') || '';
const response = await clearChatAPI(credentials, sessionId);
const response = await clearChatAPI(sessionId);
setIsDeleteChatLoading(false);
if (response.data.status !== 'Success') {
setClearHistoryData(false);
Expand Down
24 changes: 11 additions & 13 deletions frontend/src/components/Content.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -272,10 +272,7 @@ const Content: React.FC<ContentProps> = ({
const { name } = fileItem;
triggerStatusUpdateAPI(
name as string,
userCredentials?.uri,
userCredentials?.userName,
userCredentials?.password,
userCredentials?.database,
userCredentials,
updateStatusForLargeFiles
);
}
Expand Down Expand Up @@ -543,14 +540,15 @@ const Content: React.FC<ContentProps> = ({

const handleOpenGraphClick = () => {
const bloomUrl = process.env.VITE_BLOOM_URL;
const uriCoded = userCredentials?.uri.replace(/:\d+$/, '');
const connectURL = `${uriCoded?.split('//')[0]}//${userCredentials?.userName}@${uriCoded?.split('//')[1]}:${
userCredentials?.port ?? '7687'
}`;
const encodedURL = encodeURIComponent(connectURL);
const replacedUrl = bloomUrl?.replace('{CONNECT_URL}', encodedURL);
window.open(replacedUrl, '_blank');
};
let finalUrl = bloomUrl;
if (userCredentials?.database && userCredentials.uri && userCredentials.userName) {
const uriCoded = userCredentials.uri.replace(/:\d+$/, '');
const connectURL = `${uriCoded.split('//')[0]}//${userCredentials.userName}@${uriCoded.split('//')[1]}:${userCredentials.port ?? '7687'}`;
const encodedURL = encodeURIComponent(connectURL);
finalUrl = bloomUrl?.replace('{CONNECT_URL}', encodedURL);
}
window.open(finalUrl, '_blank');
};

const handleGraphView = () => {
setOpenGraphView(true);
Expand Down Expand Up @@ -884,7 +882,7 @@ const Content: React.FC<ContentProps> = ({
<DatabaseStatusIcon
isConnected={connectionStatus}
isGdsActive={isGdsActive}
uri={userCredentials && userCredentials?.uri}
uri={userCredentials?.uri}
/>
<div className='pt-1 flex gap-1 items-center'>
<div>{!hasSelections ? <StatusIndicator type='danger' /> : <StatusIndicator type='success' />}</div>
Expand Down
10 changes: 2 additions & 8 deletions frontend/src/components/FileTable.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -685,10 +685,7 @@ const FileTable: ForwardRefRenderFunction<ChildRef, FileTableProps> = (props, re
const handleSmallFile = (item: SourceNode, userCredentials: UserCredentials) => {
subscribe(
item.fileName,
userCredentials?.uri,
userCredentials?.userName,
userCredentials?.database,
userCredentials?.password,
userCredentials,
updatestatus,
updateProgress
).catch(handleFileUploadError);
Expand All @@ -697,10 +694,7 @@ const FileTable: ForwardRefRenderFunction<ChildRef, FileTableProps> = (props, re
const handleLargeFile = (item: SourceNode, userCredentials: UserCredentials) => {
triggerStatusUpdateAPI(
item.fileName,
userCredentials.uri,
userCredentials.userName,
userCredentials.password,
userCredentials.database,
userCredentials,
updateStatusForLargeFiles
);
};
Expand Down
31 changes: 18 additions & 13 deletions frontend/src/components/Layout/DrawerChatbot.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -12,20 +12,25 @@ const DrawerChatbot: React.FC<DrawerChatbotProps> = ({ isExpanded, clearHistoryD
const location = useLocation();

useEffect(() => {
if (location && location.state && Array.isArray(location.state)) {
setMessages(location.state);
} else if (
location &&
location.state &&
typeof location.state === 'object' &&
Object.keys(location.state).length > 1
) {
setUserCredentials(location.state.credential);
setIsGCSActive(location.state.isGCSActive);
setGdsActive(location.state.isgdsActive);
setIsReadOnlyUser(location.state.isReadOnlyUser);
// const localStorageData = localStorage.getItem('neo4j.connection');
// const connectionLocal = JSON.parse(localStorageData ?? '');
// if (connectionStatus && (connectionLocal.uri === userCredentials?.uri)) {
if (connectionStatus) {
if (location && location.state && Array.isArray(location.state)) {
setMessages(location.state);
} else if (
location &&
location.state &&
typeof location.state === 'object' &&
Object.keys(location.state).length > 1
) {
setUserCredentials(location.state.credential);
setIsGCSActive(location.state.isGCSActive);
setGdsActive(location.state.isgdsActive);
setIsReadOnlyUser(location.state.isReadOnlyUser);
}
}
}, [location]);
}, [location, connectionStatus]);

const getIsLoading = (messages: Messages[]) => {
return messages.length > 1 ? messages.some((msg) => msg.isTyping || msg.isLoading) : false;
Expand Down
10 changes: 5 additions & 5 deletions frontend/src/components/Layout/Header.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -47,21 +47,21 @@ const Header: React.FC<HeaderProp> = ({ chatOnly, deleteOnClick, setOpenConnecti
const isLoading = getIsLoading(messages);
if (session) {
const neo4jConnection = JSON.parse(session);
const { uri } = neo4jConnection;
const userName = neo4jConnection.user;
const { password } = neo4jConnection;
const { database } = neo4jConnection;
const { uri, userName, password, database } = neo4jConnection;
const [, port] = uri.split(':');
const encodedPassword = btoa(password);
const chatUrl = `/chat-only?uri=${encodeURIComponent(
uri
)}&user=${userName}&password=${encodedPassword}&database=${database}&port=${port}&connectionStatus=${connectionStatus}`;
navigate(chatUrl, { state: { messages, isLoading } });
} else if (connectionStatus) {
const chatUrl = `/chat-only?connectionStatus=${connectionStatus}`;
navigate(chatUrl, { state: { messages, isLoading } });
} else {
const chatUrl = `/chat-only?openModal=true`;
window.open(chatUrl, '_blank');
}
}, [messages]);
}, [messages, connectionStatus, navigate]);

const onBackButtonClick = () => {
navigate('/', { state: messages });
Expand Down
Loading