Skip to content

Commit fadf44d

Browse files
fixed: citation not display on chat history list items
1 parent c3aa999 commit fadf44d

File tree

8 files changed

+35
-104
lines changed

8 files changed

+35
-104
lines changed

src/App/backend/history/cosmosdbservice.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -158,7 +158,8 @@ async def create_message(self, uuid, conversation_id, user_id, input_message: di
158158
"updatedAt": datetime.utcnow().isoformat(),
159159
"conversationId": conversation_id,
160160
"role": input_message["role"],
161-
"content": input_message["content"],
161+
"content": input_message,
162+
162163
}
163164

164165
if self.enable_message_feedback:

src/App/frontend/src/api/api.ts

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -95,7 +95,7 @@ export const historyRead = async (convId: string): Promise<ChatMessage[]> => {
9595
return historyReadResponse.messages.map((msg: any) => ({
9696
id: msg.id,
9797
role: msg.role,
98-
content: msg.content,
98+
content: msg.content.content,
9999
date: msg.createdAt,
100100
feedback: msg.feedback ?? undefined,
101101
context: msg.context,
@@ -110,10 +110,11 @@ export const historyRead = async (convId: string): Promise<ChatMessage[]> => {
110110
const message: ChatMessage = {
111111
id: msg.id,
112112
role: msg.role,
113-
content: msg.content,
113+
content: msg.content.content,
114114
date: msg.createdAt,
115115
feedback: msg.feedback ?? undefined,
116116
context: msg.context,
117+
citations: msg.content.citations,
117118
contentType: msg.contentType,
118119
};
119120
messages.push(message);

src/App/frontend/src/components/Chat/Chat.tsx

Lines changed: 2 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -27,10 +27,7 @@ import { callConversationApi, getIsChartDisplayDefault, historyUpdate } from "..
2727
import { ChatAdd24Regular } from "@fluentui/react-icons";
2828
import { generateUUIDv4 } from "../../configs/Utils";
2929
import ChatChart from "../ChatChart/ChatChart";
30-
import { endianness } from "os";
3130
import Citations from "../Citations/Citations";
32-
import { json } from "d3";
33-
// import Citations from "../Citations/Citations";
3431

3532
type ChatProps = {
3633
onHandlePanelStates: (name: string) => void;
@@ -51,7 +48,6 @@ const Chat: React.FC<ChatProps> = ({
5148
const questionInputRef = useRef<HTMLTextAreaElement>(null);
5249
const [isChartLoading, setIsChartLoading] = useState(false)
5350
const abortFuncs = useRef([] as AbortController[]);
54-
// const [lastRagResponse, setLastRagResponse] = useState<string | null>(null);
5551
const chatMessageStreamEnd = useRef<HTMLDivElement | null>(null);
5652
const [isCharthDisplayDefault , setIsCharthDisplayDefault] = useState(false);
5753

@@ -88,7 +84,6 @@ const Chat: React.FC<ChatProps> = ({
8884
.then(async (res) => {
8985
if (!res.ok) {
9086
if (!messages) {
91-
// setAnswers([...messages, errorChatMsg]);
9287
let err: Error = {
9388
...new Error(),
9489
message: "Failure fetching current chat state.",
@@ -137,21 +132,15 @@ const Chat: React.FC<ChatProps> = ({
137132

138133

139134
const parseCitationFromMessage = (message : any) => {
140-
// console.log("parseCitationFromMessage", message);
141-
// const dummyres = '\"citations\": [ {\"content\":\"Lost phone\",\"url\":\"https://google.com\",\"title\":\"\"}, {\"content\":\"Phone freezing\",\"url\":\"\",\"title\":\"User Experience Report 1\"}, {\"content\":\"Internet speed issues\",\"url\":\"\",\"title\":\"\"}, {\"content\":\"Activation delays\",\"url\":\"\",\"title\":\"Experience Report\"}, {\"content\":\"Slow internet\",\"url\":\"\",\"title\":\"\"}, {\"content\":\"Network connectivity issues\",\"url\":\"\",\"title\":\"\"}, {\"content\":\"Poor network coverage\",\"url\":\"\",\"title\":\"abcd Report\"}, {\"content\":\"Voicemail not working\",\"url\":\"\",\"title\":\"\"} ] }';
142-
// // if (message.role === TOOL) {
143-
// message =dummyres;
135+
144136
try {
145137
message = '{'+ message
146138
const toolMessage = JSON.parse(message as string) as ToolMessageContent;
147-
// console.log("toolMessage citations", toolMessage.citations);
148139

149140
return toolMessage.citations;
150141
} catch {
151142
console.log("ERROR WHIEL PARSING TOOL CONTENT");
152-
// return [];
153143
}
154-
// }
155144
return [];
156145
};
157146
const isChartQuery = (query: string) => {
@@ -264,10 +253,6 @@ const Chat: React.FC<ChatProps> = ({
264253
runningText = text;
265254
isChartResponseReceived = true;
266255
}
267-
// if (textObj?.object?.message) {
268-
// runningText = text;
269-
// isChartResponseReceived = true;
270-
// }
271256
if (textObj?.error) {
272257
hasError = true;
273258
runningText = text;
@@ -509,7 +494,6 @@ const Chat: React.FC<ChatProps> = ({
509494
} else if (isChartQuery(userMessage)) {
510495
runningText = runningText + textValue;
511496
} else if (typeof parsed === "object" && !hasError) {
512-
console.log(":::parsed::::",parsed);
513497
const responseContent = parsed?.choices?.[0]?.messages?.[0]?.content;
514498

515499
const answerKey = `"answer":`;
@@ -657,6 +641,7 @@ const Chat: React.FC<ChatProps> = ({
657641
];
658642
}
659643
}
644+
console.log("line 66o:updatedMessages:::", updatedMessages)
660645
saveToDB(updatedMessages, conversationId, isChatReq);
661646
} catch (e) {
662647
console.log("Catched with an error while chat and save", e);
@@ -733,10 +718,6 @@ const Chat: React.FC<ChatProps> = ({
733718
dispatch({ type: actionConstants.NEW_CONVERSATION_START });
734719
};
735720
const { messages, citations } = state.chat;
736-
useEffect(()=>{
737-
// console.log('messages::', messages)
738-
// console.log('citations::', citations)
739-
},[citations, messages]);
740721
return (
741722
<div className="chat-container">
742723
<div className="chat-header">
@@ -800,7 +781,6 @@ const Chat: React.FC<ChatProps> = ({
800781
);
801782
}
802783
if (typeof msg.content === "string") {
803-
// console.log("mesg.conent:::", msg)
804784
return (
805785
<div className="assistant-message">
806786
<ReactMarkdown

src/App/frontend/src/components/ChatHistoryListItemGroups/ChatHistoryListItemGroups.tsx

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,6 @@ import {
99
StackItem,
1010
Text,
1111
} from "@fluentui/react";
12-
// import _ from "lodash";
1312
import styles from "./ChatHistoryListItemGroups.module.css";
1413
import { ChatHistoryListItemCell } from "../ChatHistoryListItemCell/ChatHistoryListItemCell";
1514
import { Conversation } from "../../types/AppTypes";

src/App/frontend/src/components/ChatHistoryPanel/ChatHistoryPanel.tsx

Lines changed: 0 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -136,15 +136,6 @@ export const ChatHistoryPanel: React.FC<ChatHistoryPanelProps> = (props) => {
136136
/>
137137
</Stack>
138138

139-
{/* <Stack horizontal>
140-
<CommandBarButton
141-
iconProps={{ iconName: "Cancel" }}
142-
title={"Hide"}
143-
aria-label={"hide button"}
144-
role="button"
145-
// onClick={() => setShowHistoryPanel(false)}
146-
/>
147-
</Stack> */}
148139
</Stack>
149140
</Stack>
150141
<Stack

src/App/frontend/src/components/CitationPanel/CitationPanel.tsx

Lines changed: 4 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,9 @@
11
import React, { useMemo, useState } from 'react';
2-
// import sampledata from '../../sampleResponseCitation.json';
32
import ReactMarkdown from 'react-markdown';
43
import { Stack } from '@fluentui/react';
54
import { DismissRegular } from '@fluentui/react-icons';
65
import remarkGfm from "remark-gfm";
76
import rehypeRaw from "rehype-raw";
8-
// import styles from "./Chat.module.css";
9-
// import { AskResponse } from '../../api/models';
107
import { useAppContext } from '../../state/useAppContext';
118
import { actionConstants } from '../../state/ActionConstants';
129
import "./CitationPanel.css";
@@ -15,32 +12,19 @@ interface Props {
1512
}
1613

1714
const CitationPanel = ({ activeCitation }: Props) => {
18-
// console.log("activeCitation", activeCitation);
1915
const { dispatch } = useAppContext()
20-
// const [activeCitation, setActiveCitation] =
21-
// useState<
22-
// [
23-
// content: string,
24-
// id: string,
25-
// title: string,
26-
// filepath: string,
27-
// url: string,
28-
// metadata: string,
29-
// ]
30-
// >();
31-
16+
3217
const onCloseCitation = () => {
3318
dispatch({ type: actionConstants.UPDATE_CITATION,payload: { activeCitation: null, showCitation: false }})
3419
}
3520
return (
3621
<div className='citationPanel'>
3722

3823
<Stack.Item
39-
// className={`${styles.citationPanel} ${styles.mobileStyles}`}
24+
4025
>
4126
<Stack
4227
horizontal
43-
// className={styles.citationPanelHeaderContainer}
4428
horizontalAlign="space-between"
4529
verticalAlign="center"
4630
>
@@ -53,7 +37,6 @@ const CitationPanel = ({ activeCitation }: Props) => {
5337
}}
5438
>
5539

56-
{/* // className={styles.citationPanelHeader} */}
5740
Citations
5841
</div>
5942
<DismissRegular
@@ -64,23 +47,16 @@ const CitationPanel = ({ activeCitation }: Props) => {
6447
: () => { }
6548
}
6649
tabIndex={0}
67-
// className={styles.citationPanelDismiss}
6850
onClick={onCloseCitation}
6951
/>
7052
</Stack>
7153
<h5
72-
// className={`${styles.citationPanelTitle} ${styles.mobileCitationPanelTitle}`}
54+
7355
>
7456
{activeCitation.title}
7557
</h5>
76-
{/* <div className='citationPanelInner'
77-
// className={`${styles.citationPanelDisclaimer} ${styles.mobileCitationPanelDisclaimer}`}
78-
>
79-
Tables, images, and other special formatting not shown in this
80-
preview. Please follow the link to review the original document.
81-
</div> */}
58+
8259
<ReactMarkdown
83-
// className={`${styles.citationPanelContent} ${styles.mobileCitationPanelContent}`}
8460
children={activeCitation?.content}
8561
remarkPlugins={[remarkGfm]}
8662
rehypePlugins={[rehypeRaw]}

src/App/frontend/src/components/Citations/AnswerParser.tsx

Lines changed: 24 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,3 @@
1-
// import { AskResponse, Citation } from "../../api";
21
import { cloneDeep } from "lodash-es";
32
import { AskResponse, Citation } from "../../types/AppTypes";
43

@@ -17,30 +16,30 @@ const isDuplicate = (citation: Citation,citationIndex:string) => {
1716

1817
export function parseAnswer(answer: AskResponse): ParsedAnswer {
1918
let answerText = answer.answer;
20-
// const citationLinks = answerText.match(/\[(doc\d\d?\d?)]/g);
21-
22-
// const lengthDocN = "[doc".length;
23-
24-
// filteredCitations = [] as Citation[];
25-
// let citationReindex = 0;
26-
// citationLinks?.forEach(link => {
27-
// // Replacing the links/citations with number
28-
// let citationIndex = link.slice(lengthDocN, link.length - 1);
29-
// let citation = cloneDeep(answer.citations[Number(citationIndex) - 1]) as Citation;
30-
31-
// if (citation !== undefined && !isDuplicate(citation, citationIndex)) {
32-
// answerText = answerText.replaceAll(link, ` ^${++citationReindex}^ `);
33-
// citation.id = citationIndex; // original doc index to de-dupe
34-
// citation.reindex_id = citationReindex.toString(); // reindex from 1 for display
35-
// filteredCitations.push(citation);
36-
// }else{
37-
// // Replacing duplicate citation with original index
38-
// let matchingCitation = filteredCitations.find((ct) => citation?.chunk_id == ct?.chunk_id);
39-
// if (matchingCitation) {
40-
// answerText= answerText.replaceAll(link, ` ^${matchingCitation.reindex_id}^ `)
41-
// }
42-
// }
43-
// })
19+
const citationLinks = answerText?.match(/\[(doc\d\d?\d?)]/g);
20+
21+
const lengthDocN = "[doc".length;
22+
23+
filteredCitations = [] as Citation[];
24+
let citationReindex = 0;
25+
citationLinks?.forEach(link => {
26+
// Replacing the links/citations with number
27+
let citationIndex = link.slice(lengthDocN, link?.length - 1);
28+
let citation = cloneDeep(answer.citations[Number(citationIndex) - 1]) as Citation;
29+
30+
if (citation !== undefined && !isDuplicate(citation, citationIndex)) {
31+
answerText = answerText?.replaceAll(link, ` ^${++citationReindex}^ `);
32+
citation.id = citationIndex; // original doc index to de-dupe
33+
citation.reindex_id = citationReindex.toString(); // reindex from 1 for display
34+
filteredCitations.push(citation);
35+
}else{
36+
// Replacing duplicate citation with original index
37+
let matchingCitation = filteredCitations.find((ct) => citation?.chunk_id == ct?.chunk_id);
38+
if (matchingCitation) {
39+
answerText= answerText.replaceAll(link, ` ^${matchingCitation.reindex_id}^ `)
40+
}
41+
}
42+
})
4443

4544

4645
return {

src/App/frontend/src/components/Citations/Citations.tsx

Lines changed: 0 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,7 @@
11
import React, { useMemo } from 'react';
2-
// import sampledata from '../../sampleResponseCitation.json';
3-
// import { AskResponse, Citation } from '../../api/models';
42
import { parseAnswer } from './AnswerParser';
53
import { useAppContext } from '../../state/useAppContext';
64
import { actionConstants } from '../../state/ActionConstants';
7-
// import { parseAnswer } from "./AnswerParser";
8-
// import styles from "./Citations.css";
95
import "./Citations.css";
106
import { AskResponse, Citation } from '../../types/AppTypes';
117

@@ -17,29 +13,17 @@ interface Props {
1713
}
1814

1915
const Citations = ({ answer, index }: Props) => {
20-
// console.log("answer", answer);
2116

2217
const { state, dispatch } = useAppContext();
2318
const parsedAnswer = useMemo(() => parseAnswer(answer), [answer]);
24-
// console.log("parsedAnswer::", parsedAnswer);
2519
const filePathTruncationLimit = 50;
2620
const createCitationFilepath = (
2721
citation: Citation,
2822
index: number,
2923
truncate: boolean = false
3024
) => {
3125
let citationFilename = "";
32-
33-
// if (citation.filepath && citation.chunk_id != null) {
34-
// if (truncate && citation.filepath.length > filePathTruncationLimit) {
35-
// const citationLength = citation.filepath.length;
36-
// citationFilename = `${citation.filepath.substring(0, 20)}...${citation.filepath.substring(citationLength - 20)} - Part ${citation.chunk_id}`;
37-
// } else {
38-
// citationFilename = `${citation.filepath} - Part ${citation.chunk_id}`;
39-
// }
40-
// } else {
4126
citationFilename = citation.title ? (citation.title ?? `Citation ${index}`) : `Citation ${index}`;
42-
// }
4327
return citationFilename;
4428
};
4529

0 commit comments

Comments
 (0)