File size: 1,686 Bytes
8b1e853
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
from langchain_openai import ChatOpenAI
from langchain_core.messages import HumanMessage
from langchain_core.prompts import ChatPromptTemplate
from langchain_core.output_parsers import StrOutputParser
from langgraph.graph import StateGraph
from typing_extensions import Annotated, TypedDict
from langgraph.graph import add_messages, END
from langgraph.checkpoint.memory import MemorySaver
from dotenv import load_dotenv

load_dotenv()

llm = ChatOpenAI(model="gpt-4o", temperature=0)
memory = MemorySaver()

class State(TypedDict):
    previous_questions: Annotated[list, add_messages]
    context:str

prompt = ChatPromptTemplate.from_template(
    """
    You are an expert at ingesting documents and creating questions for a medical questionnaire to be answered by patients with a high school level education. Given the following context that should contain medical questions, and from only this context extract all medical questions separated by '|' that would be appropriate for a patient to answer. Indicate if the question is a multiple choice and the include the possible choices. If there are no medical questions in the context, output 'None'.

    Context:
    {context}
    """
)

def create_questions(state):
    results = (prompt | llm | StrOutputParser()).invoke(state)
    questions = results.split("|")
   
    questions = [q for q in questions if q and q != 'None']
    return {"previous_questions":questions, "context":state.get("context","") or ''}

graph = StateGraph(State)

graph.add_node("create_questions", create_questions)
graph.set_entry_point("create_questions")
graph.add_edge("create_questions", END)
workflow = graph.compile(checkpointer=memory)