Skip to content

Commit

Permalink
feat: close #34 closes better prompt design for questions #21
Browse files Browse the repository at this point in the history
  • Loading branch information
wangqianwen0418 committed Mar 18, 2024
1 parent e92bfca commit c90d855
Show file tree
Hide file tree
Showing 6 changed files with 139 additions and 35 deletions.
1 change: 1 addition & 0 deletions app/api/chat/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,7 @@ export async function POST(req: Request) {
You are an expert in healthcare domain and need to help user to answer the healthcare related questions.
After the response, please summary the entity/terms and their relations (tripes) in your response.
The entities/terms can only be the following types: Dietary Supplement, Drugs, Disease, Symptom, Gene.
Use exactly the same name for summaring the entities/terms and their relations as used in your responses
Keep your response short and concise, and the number of triples mentioned in the response should be less than ${num_triples}.
Please return your response in four parts:
the 1st part is your response to user question;
Expand Down
7 changes: 6 additions & 1 deletion components/chat-list.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,18 +3,21 @@ import React, { use, useCallback, useEffect } from 'react'
import { Message } from 'ai'
import { ChatMessage } from '@/components/chat-message'
import { useViewMode } from '@/components/ui/view-mode'
import { CustomGraphEdge, CustomGraphNode } from '@/lib/types'

export interface ChatListProps {
messages: Message[]
activeStep: number
nodes: any
nodes: CustomGraphNode[]
edges: CustomGraphEdge[]
clickedNode: any
}

export function ChatList({
messages,
activeStep,
nodes,
edges,
clickedNode,
}: ChatListProps) {
const { isPaneView } = useViewMode()
Expand All @@ -34,6 +37,7 @@ export function ChatList({
key={index}
message={message}
nodes={message.role=='user'?[]:nodes}
edges={message.role=='user'?[]:edges}
clickedNode={clickedNode}
/>
))}
Expand All @@ -45,6 +49,7 @@ export function ChatList({
key={index}
message={message}
nodes={message.role=='user'?[]:nodes}
edges={message.role=='user'?[]:edges}
clickedNode={clickedNode}
/>
))}
Expand Down
12 changes: 11 additions & 1 deletion components/chat-message.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -11,18 +11,20 @@ import { CodeBlock } from '@/components/ui/codeblock'
import { MemoizedReactMarkdown } from '@/components/markdown'
import { IconOpenAI, IconUser } from '@/components/ui/icons'
import { ChatMessageActions } from '@/components/chat-message-actions'
import { CustomGraphNode } from '@/lib/types'
import { CustomGraphEdge, CustomGraphNode } from '@/lib/types'

export interface ChatMessageProps {
message: Message
nodes: CustomGraphNode[]
edges: CustomGraphEdge[]
clickedNode: any
}


export function ChatMessage({
message,
nodes,
edges,
clickedNode,
...props
}: ChatMessageProps) {
Expand Down Expand Up @@ -122,6 +124,14 @@ export function ChatMessage({
}
})

edges.forEach(edge => {
processedContent = processedContent.replace(
edge.label as string,
`<mark class="underline bg-white">${edge.label}</mark>`
)

})

return processedContent
}

Expand Down
150 changes: 118 additions & 32 deletions components/chat.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,8 @@ import {
recommendationsAtom,
backendDataAtom,
keywordsListAnswerAtom,
keywordsListQuestionAtom
keywordsListQuestionAtom,
gptTriplesAtom
} from '@/lib/state'
import { fetchBackendData, categoryColorMapping } from '@/lib/utils'
import dagre from 'dagre'
Expand Down Expand Up @@ -145,6 +146,7 @@ export function Chat({ id, initialMessages }: ChatProps) {
const [keywordsQuestion, setKeywordsQuestion] = useAtom(
keywordsListQuestionAtom
)
const [gptTriples, setGptTriples] = useAtom(gptTriplesAtom)

const router = useRouter()
const path = usePathname()
Expand Down Expand Up @@ -218,6 +220,10 @@ export function Chat({ id, initialMessages }: ChatProps) {
// const newkeywordsListQuestion =
// thirdPart.match(/\[(.*?)\]/)?.[1].split(' | ') || []

if(secondPart.length> 0){
setGptTriples(secondPart)
}

const newkeywordsListAnswer = [... new Set( secondPart.map((d:string[])=>[d[0], d[2]]).flat())]
const newkeywordsListQuestion = thirdPart
setKeywordsAnswer(newkeywordsListAnswer)
Expand Down Expand Up @@ -384,29 +390,114 @@ export function Chat({ id, initialMessages }: ChatProps) {
currentStep
)

setNodes(currentNodes => {
const updatedNodes = [...currentNodes]
newNodes.forEach(newNode => {
if (!updatedNodes.find(node => node.id === newNode.id)) {
updatedNodes.push({
...newNode,
position: { x: Math.random() * 400, y: Math.random() * 400 },
step: currentStep
})
}
})
return updatedNodes
let updatedNodes = [...nodes], updatedEdges = [...edges]
newNodes.forEach(newNode => {
if (!updatedNodes.find(node => node.id === newNode.id)) {
updatedNodes.push({
...newNode,
position: { x: 0, y: 0 },
step: currentStep
})
}
})

newEdges.forEach(newEdge => {
if (!updatedEdges.find(edge => edge.id === newEdge.id)) {
updatedEdges.push({ ...newEdge, step: currentStep })
}
})

setEdges(currentEdges => {
const updatedEdges = [...currentEdges]
newEdges.forEach(newEdge => {
if (!updatedEdges.find(edge => edge.id === newEdge.id)) {
updatedEdges.push({ ...newEdge, step: currentStep })
gptTriples.forEach((triple, i) => {
const [source, relation, target] = triple
const sourceNode = updatedNodes.find(node => node.data.gptName.toLowerCase() === source.toLowerCase())
const targetNode = updatedNodes.find(node => node.data.gptName.toLowerCase() === target.toLowerCase())
if (sourceNode && targetNode) {
const edgeId = `e${sourceNode.id}-${targetNode.id}`
var findEdgeIndex = updatedEdges.findIndex(edge => edge.id === edgeId)
if (findEdgeIndex === -1) {
updatedEdges.push({
id: edgeId,
source: sourceNode.id,
target: targetNode.id,
label: relation,
data: { papers: { [relation]: [] } },
type: 'custom',
category: 'NotFind',
step: currentStep,
style: { opacity: 1 }
})
}else{
updatedEdges[findEdgeIndex] = {
...updatedEdges[findEdgeIndex],
label: relation, // use gpt relation
}
}
})
return updatedEdges
}
if (!sourceNode){
updatedNodes.push({
id: source,
data: { label: source, kgName: '', gptName: source },
position: { x: 0, y: 0 },
type: 'default',
category: 'NotFind',
style: {
opacity: 1,
background: '#ffffff',
border: '1px solid #222'
},
step: currentStep,
})
}
if (!targetNode){
updatedNodes.push({
id: target,
data: { label: target, kgName: '', gptName: target },
position: { x: 0, y: 0 },
type: 'default',
category: 'gptNode',
style: {
opacity: 1,
background: '#ffffff',
border: '1px solid #222'
},
step: currentStep,
})
}
})

console.info('Updated Nodes:', updatedNodes, 'Updated Edges:', updatedEdges, gptTriples)

setNodes(updatedNodes)
setEdges(updatedEdges)


// setNodes(currentNodes => {
// const updatedNodes = [...currentNodes]
// newNodes.forEach(newNode => {
// if (!updatedNodes.find(node => node.id === newNode.id)) {
// updatedNodes.push({
// ...newNode,
// position: { x: Math.random() * 400, y: Math.random() * 400 },
// step: currentStep
// })
// }
// })
// return updatedNodes
// })

// setEdges(currentEdges => {
// const updatedEdges = [...currentEdges]
// newEdges.forEach(newEdge => {
// if (!updatedEdges.find(edge => edge.id === newEdge.id)) {
// updatedEdges.push({ ...newEdge, step: currentStep })
// }
// })
// gptTriples.current.forEach((triple, i) => {
// const [source, relation, target] = triple

// })
// return updatedEdges
// })
},
[setNodes, setEdges]
)
Expand Down Expand Up @@ -489,11 +580,12 @@ export function Chat({ id, initialMessages }: ChatProps) {
}
}, [backendData, appendDataToFlow, setRecommendations, activeStep])

useEffect(() => {
// Perform actions based on updated keywordsAnswer and keywordsQuestion
console.log('Keywords Answer Updated:', keywordsAnswer)
console.log('Keywords Question Updated:', keywordsQuestion)
}, [keywordsAnswer, keywordsQuestion])
// useEffect(() => {
// // Perform actions based on updated keywordsAnswer and keywordsQuestion
// console.log('Keywords Answer Updated:', keywordsAnswer)
// console.log('Keywords Question Updated:', keywordsQuestion)
// console.info('GPT Triples:', gptTriples.current)
// }, [keywordsAnswer, keywordsQuestion])

const StopRegenerateButton = isLoading ? (
<Button
Expand All @@ -516,13 +608,6 @@ export function Chat({ id, initialMessages }: ChatProps) {
</Button>
)

const customEdgeTypes = useMemo(
() => ({
custom: CustomEdge
}),
[]
)

useEffect(() => {
const handleResize = () => {
updateLayout()
Expand Down Expand Up @@ -588,6 +673,7 @@ export function Chat({ id, initialMessages }: ChatProps) {
messages={messages}
activeStep={activeStep}
nodes={nodes}
edges={edges}
clickedNode={clickedNode}
/>
{StopRegenerateButton}
Expand Down
1 change: 1 addition & 0 deletions lib/state.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,3 +7,4 @@ export const recommendationsAtom = atom([] as Recommendation[])
export const backendDataAtom = atom({} as BackendData)
export const keywordsListAnswerAtom = atom([] as string[])
export const keywordsListQuestionAtom = atom([] as string[])
export const gptTriplesAtom = atom([] as string[])
3 changes: 2 additions & 1 deletion lib/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,8 @@ export const categoryColorMapping: { [key: string]: string } = {
Device: '#f28e2c', // Orange
Object: '#e15759', // Red
Organization: '#76b7b2', // Cyan
Phenomenon: '#59a14f' // Green
Phenomenon: '#59a14f', // Green
NotFind: '#666' //gray
// Add more label types and colors as needed
}

Expand Down

0 comments on commit c90d855

Please sign in to comment.