aie4-final / backend /app /upload_pdf /questions_agent.py
richlai's picture
add files
8b1e853
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)