Files
ds_erp_ai/ds_fire_fighter/notebooks/test.ipynb
T

3121 lines
298 KiB
Plaintext
Raw Normal View History

2025-02-06 20:12:43 +00:00
{
"cells": [
{
"cell_type": "code",
"execution_count": 5,
"metadata": {},
"outputs": [],
"source": [
"import os\n",
"from spire.doc import Document, FileFormat\n",
"from langchain_community.document_loaders import PyPDFLoader\n",
"\n",
"def convert_word_to_pdf(doc_path: str) -> str:\n",
" \"\"\"\n",
" Convert a .doc or .docx file to PDF using Spire.Doc.\n",
" \n",
" Args:\n",
" doc_path (str): The path to the .doc or .docx file.\n",
"\n",
" Returns:\n",
" str: The path to the converted PDF file.\n",
" \"\"\"\n",
" pdf_path = os.path.splitext(doc_path)[0] + '.pdf'\n",
" \n",
" # Create a Document object\n",
" document = Document()\n",
" # Load the Word document\n",
" document.LoadFromFile(doc_path)\n",
" # Save as PDF\n",
" document.SaveToFile(pdf_path, FileFormat.PDF)\n",
" document.Close()\n",
" \n",
" return pdf_path\n",
"\n",
"def load_document(file_path: str):\n",
" \"\"\"\n",
" Utility function to load a PDF, DOCX, or DOC file by first converting it to PDF.\n",
"\n",
" Args:\n",
" file_path (str): The path to the file to load.\n",
"\n",
" Returns:\n",
" List[Document]: A list of Document objects representing the contents of the file.\n",
" \"\"\"\n",
" extension = os.path.splitext(file_path)[1].lower()\n",
" \n",
" if extension in ['.doc', '.docx']:\n",
" # Convert .doc or .docx to PDF first\n",
" pdf_path = convert_word_to_pdf(file_path)\n",
" loader = PyPDFLoader(pdf_path)\n",
" elif extension == '.pdf':\n",
" loader = PyPDFLoader(file_path)\n",
" else:\n",
" raise ValueError(f\"Unsupported file type: {extension}. Only .pdf, .docx, and .doc are supported.\")\n",
" \n",
" return loader.load()"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": []
},
{
"cell_type": "code",
"execution_count": 4,
"metadata": {},
"outputs": [],
"source": [
"from langchain_community.document_loaders import WebBaseLoader\n",
"from langchain_community.vectorstores import FAISS\n",
"from langchain_openai import OpenAIEmbeddings\n",
"from langchain_text_splitters import RecursiveCharacterTextSplitter\n",
"from langchain.schema import Document\n",
"import json\n",
"import os\n",
"\n",
"# Load questions and themes\n",
"question_path = \"../data/config_files/questions.json\"\n",
"theme_path = \"../data/config_files/theme_context.json\"\n",
"with open(question_path, \"r\") as f:\n",
" questions = json.load(f)\n",
"\n",
"with open(theme_path, \"r\") as f:\n",
" themes = json.load(f)\n",
"\n",
"def load_document(file_path: str):\n",
" extension = os.path.splitext(file_path)[1].lower()\n",
" \n",
" if extension in ['.doc', '.docx']:\n",
" # Convert .doc or .docx to PDF first\n",
" pdf_path = convert_word_to_pdf(file_path)\n",
" loader = PyPDFLoader(pdf_path)\n",
" elif extension == '.pdf':\n",
" loader = PyPDFLoader(file_path)\n",
" else:\n",
" raise ValueError(f\"Unsupported file type: {extension}. Only .pdf, .docx, and .doc are supported.\")\n",
" \n",
" return loader.load()\n",
"\n",
"# Create text splitter\n",
"text_splitter = RecursiveCharacterTextSplitter.from_tiktoken_encoder(\n",
" chunk_size=100, chunk_overlap=50\n",
")\n",
"\n",
"# Load and split resume document\n",
"docs = load_document('../upload_folder/Resume_-_Erika_Kiviaho.pdf')\n",
"resume_splits = text_splitter.split_documents(docs)\n",
"\n",
"# Create vector store for resume\n",
"resume_vectorstore = FAISS.from_documents(\n",
" documents=resume_splits,\n",
" embedding=OpenAIEmbeddings(),\n",
")\n",
"resume_retriever = resume_vectorstore.as_retriever()\n",
"\n",
"# Prepare questions for vectorDB - Convert dictionary to Document objects\n",
"questions_docs = [\n",
" Document(\n",
" page_content=str(value),\n",
" metadata={\"question_id\": key}\n",
" )\n",
" for key, value in questions.items()\n",
"]\n",
"questions_splits = text_splitter.split_documents(questions_docs)\n",
"\n",
"# Create vector store for questions\n",
"questions_vectorstore = FAISS.from_documents(\n",
" documents=questions_splits,\n",
" embedding=OpenAIEmbeddings(),\n",
")\n",
"questions_retriever = questions_vectorstore.as_retriever()\n",
"\n",
"from langchain.tools.retriever import create_retriever_tool\n",
"\n",
"# Create retriever tool for resume\n",
"resume_retriever_tool = create_retriever_tool(\n",
" resume_retriever,\n",
" \"retrieve_resume_info\",\n",
" \"Search and return information from the user's resume.\"\n",
")\n",
"\n",
"# Create retriever tool for questions\n",
"questions_retriever_tool = create_retriever_tool(\n",
" questions_retriever,\n",
" \"retrieve_questions_info\",\n",
" \"Search and return information about general questions.\"\n",
")\n",
"\n",
"tools = [resume_retriever_tool, questions_retriever_tool]"
]
},
{
"cell_type": "code",
"execution_count": 6,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"\n",
"Starting practice session for theme: Customer Service\n",
"I'll ask you several questions, then help create a STARTPOP response.\n",
"Type your responses when prompted, or 'quit' to end.\n",
"\n"
]
},
{
"ename": "TypeError",
"evalue": "StateGraph.add_edge() takes 3 positional arguments but 4 were given",
"output_type": "error",
"traceback": [
"\u001b[0;31m---------------------------------------------------------------------------\u001b[0m",
"\u001b[0;31mTypeError\u001b[0m Traceback (most recent call last)",
"Cell \u001b[0;32mIn[6], line 196\u001b[0m\n\u001b[1;32m 193\u001b[0m \u001b[38;5;28mprint\u001b[39m(\u001b[38;5;124m\"\u001b[39m\u001b[38;5;124mI\u001b[39m\u001b[38;5;124m'\u001b[39m\u001b[38;5;124mll ask you several questions, then help create a STARTPOP response.\u001b[39m\u001b[38;5;124m\"\u001b[39m)\n\u001b[1;32m 194\u001b[0m \u001b[38;5;28mprint\u001b[39m(\u001b[38;5;124m\"\u001b[39m\u001b[38;5;124mType your responses when prompted, or \u001b[39m\u001b[38;5;124m'\u001b[39m\u001b[38;5;124mquit\u001b[39m\u001b[38;5;124m'\u001b[39m\u001b[38;5;124m to end.\u001b[39m\u001b[38;5;130;01m\\n\u001b[39;00m\u001b[38;5;124m\"\u001b[39m)\n\u001b[0;32m--> 196\u001b[0m \u001b[38;5;28;01mfor\u001b[39;00m state \u001b[38;5;129;01min\u001b[39;00m \u001b[43mrun_theme_practice\u001b[49m\u001b[43m(\u001b[49m\u001b[43mtheme\u001b[49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[43mresume_retriever\u001b[49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[43mquestions_retriever\u001b[49m\u001b[43m)\u001b[49m:\n\u001b[1;32m 197\u001b[0m \u001b[38;5;28;01mif\u001b[39;00m \u001b[38;5;28misinstance\u001b[39m(state\u001b[38;5;241m.\u001b[39mmessages[\u001b[38;5;241m-\u001b[39m\u001b[38;5;241m1\u001b[39m], AIMessage):\n\u001b[1;32m 198\u001b[0m \u001b[38;5;28mprint\u001b[39m(\u001b[38;5;124m\"\u001b[39m\u001b[38;5;130;01m\\n\u001b[39;00m\u001b[38;5;124mAssistant:\u001b[39m\u001b[38;5;124m\"\u001b[39m, state\u001b[38;5;241m.\u001b[39mmessages[\u001b[38;5;241m-\u001b[39m\u001b[38;5;241m1\u001b[39m]\u001b[38;5;241m.\u001b[39mcontent)\n",
"Cell \u001b[0;32mIn[6], line 175\u001b[0m, in \u001b[0;36mrun_theme_practice\u001b[0;34m(theme, resume_retriever, questions_retriever)\u001b[0m\n\u001b[1;32m 172\u001b[0m \u001b[38;5;28;01mdef\u001b[39;00m\u001b[38;5;250m \u001b[39m\u001b[38;5;21mrun_theme_practice\u001b[39m(theme: \u001b[38;5;28mstr\u001b[39m, resume_retriever, questions_retriever):\n\u001b[1;32m 173\u001b[0m \u001b[38;5;250m \u001b[39m\u001b[38;5;124;03m\"\"\"Runs a practice session for a specific theme\"\"\"\u001b[39;00m\n\u001b[0;32m--> 175\u001b[0m practice_bot \u001b[38;5;241m=\u001b[39m \u001b[43mcreate_practice_assistant\u001b[49m\u001b[43m(\u001b[49m\u001b[43mtheme\u001b[49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[43mresume_retriever\u001b[49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[43mquestions_retriever\u001b[49m\u001b[43m)\u001b[49m\n\u001b[1;32m 177\u001b[0m \u001b[38;5;66;03m# Initialize state\u001b[39;00m\n\u001b[1;32m 178\u001b[0m initial_state \u001b[38;5;241m=\u001b[39m PracticeState(\n\u001b[1;32m 179\u001b[0m messages\u001b[38;5;241m=\u001b[39m[\n\u001b[1;32m 180\u001b[0m SystemMessage(content\u001b[38;5;241m=\u001b[39m\u001b[38;5;124mf\u001b[39m\u001b[38;5;124m\"\u001b[39m\u001b[38;5;124mStarting practice session for theme: \u001b[39m\u001b[38;5;132;01m{\u001b[39;00mtheme\u001b[38;5;132;01m}\u001b[39;00m\u001b[38;5;124m\"\u001b[39m),\n\u001b[0;32m (...)\u001b[0m\n\u001b[1;32m 183\u001b[0m theme\u001b[38;5;241m=\u001b[39mtheme\n\u001b[1;32m 184\u001b[0m )\n",
"Cell \u001b[0;32mIn[6], line 164\u001b[0m, in \u001b[0;36mcreate_practice_assistant\u001b[0;34m(theme, resume_retriever, questions_retriever)\u001b[0m\n\u001b[1;32m 161\u001b[0m workflow\u001b[38;5;241m.\u001b[39madd_node(\u001b[38;5;124m\"\u001b[39m\u001b[38;5;124mgenerate_startpop\u001b[39m\u001b[38;5;124m\"\u001b[39m, generate_startpop)\n\u001b[1;32m 163\u001b[0m \u001b[38;5;66;03m# Add edges\u001b[39;00m\n\u001b[0;32m--> 164\u001b[0m \u001b[43mworkflow\u001b[49m\u001b[38;5;241;43m.\u001b[39;49m\u001b[43madd_edge\u001b[49m\u001b[43m(\u001b[49m\u001b[38;5;124;43m\"\u001b[39;49m\u001b[38;5;124;43mshould_continue\u001b[39;49m\u001b[38;5;124;43m\"\u001b[39;49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[38;5;124;43m\"\u001b[39;49m\u001b[38;5;124;43mcontinue_questions\u001b[39;49m\u001b[38;5;124;43m\"\u001b[39;49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[38;5;124;43m\"\u001b[39;49m\u001b[38;5;124;43mcontinue_questions\u001b[39;49m\u001b[38;5;124;43m\"\u001b[39;49m\u001b[43m)\u001b[49m\n\u001b[1;32m 165\u001b[0m workflow\u001b[38;5;241m.\u001b[39madd_edge(\u001b[38;5;124m\"\u001b[39m\u001b[38;5;124mshould_continue\u001b[39m\u001b[38;5;124m\"\u001b[39m, \u001b[38;5;124m\"\u001b[39m\u001b[38;5;124mgenerate_startpop\u001b[39m\u001b[38;5;124m\"\u001b[39m, \u001b[38;5;124m\"\u001b[39m\u001b[38;5;124mgenerate_startpop\u001b[39m\u001b[38;5;124m\"\u001b[39m)\n\u001b[1;32m 166\u001b[0m workflow\u001b[38;5;241m.\u001b[39madd_edge(\u001b[38;5;124m\"\u001b[39m\u001b[38;5;124mget_next_question\u001b[39m\u001b[38;5;124m\"\u001b[39m, \u001b[38;5;124m\"\u001b[39m\u001b[38;5;124mprocess_response\u001b[39m\u001b[38;5;124m\"\u001b[39m, \u001b[38;5;124m\"\u001b[39m\u001b[38;5;124mprocess_response\u001b[39m\u001b[38;5;124m\"\u001b[39m)\n",
"\u001b[0;31mTypeError\u001b[0m: StateGraph.add_edge() takes 3 positional arguments but 4 were given"
]
}
],
"source": [
"from typing import List, Dict\n",
"from pydantic import BaseModel, Field\n",
"from langchain_core.messages import BaseMessage, HumanMessage, AIMessage, SystemMessage\n",
"from langchain_openai import ChatOpenAI\n",
"from langchain_community.tools.tavily_search import TavilySearchResults\n",
"from langgraph.graph import StateGraph, END\n",
"from langgraph.checkpoint.memory import MemorySaver\n",
"\n",
"class PracticeState(BaseModel):\n",
" \"\"\"Tracks the state of the practice session\"\"\"\n",
" messages: List[BaseMessage] = Field(default_factory=list)\n",
" theme: str\n",
" questions_asked: int = 0\n",
" gathered_responses: List[str] = Field(default_factory=list)\n",
" ready_for_startpop: bool = False\n",
"\n",
"def create_practice_assistant(theme: str, resume_retriever, questions_retriever):\n",
" \"\"\"Creates a practice assistant for a specific interview theme\"\"\"\n",
" \n",
" model = ChatOpenAI(temperature=0.7, model=\"gpt-4-turbo-preview\")\n",
" memory = MemorySaver()\n",
"\n",
" # Core system prompt for question generation\n",
" QUESTION_PROMPT = \"\"\"You are an AI assistant helping prepare for a firefighter interview, focusing on the theme: {theme}.\n",
"\n",
" Resume Context:\n",
" {resume_context}\n",
"\n",
" Sample Questions for this Theme:\n",
" {questions_context}\n",
"\n",
" Previous Questions and Responses:\n",
" {conversation_history}\n",
"\n",
" Generate a focused question that:\n",
" 1. Relates to the candidate's background from their resume\n",
" 2. Aligns with the current theme\n",
" 3. Encourages STAR/STARTPOP format responses\n",
" 4. Builds on previous responses\n",
" 5. Helps gather material for a strong STARTPOP response\n",
"\n",
" Ask only ONE question and make it conversational and encouraging.\"\"\"\n",
"\n",
" # STARTPOP generation prompt\n",
" STARTPOP_PROMPT = \"\"\"Based on all the responses gathered during our practice session, let's create a strong STARTPOP response for the theme: {theme}\n",
"\n",
" Theme: {theme}\n",
" Collected Responses: {responses}\n",
" Resume Context: {resume_context}\n",
"\n",
" Create a polished STARTPOP response that:\n",
" 1. Uses the best examples from the practice session\n",
" 2. Incorporates relevant experience from the resume\n",
" 3. Follows the exact STARTPOP format:\n",
"\n",
" Situation:\n",
" - [Specific context and background]\n",
"\n",
" Task:\n",
" - [Clear objectives and responsibilities]\n",
"\n",
" Action:\n",
" - [Both potential negative approaches and chosen positive actions]\n",
"\n",
" Results:\n",
" - [Concrete outcomes with timeframes]\n",
"\n",
" Transitions:\n",
" - [Professional firefighting terminology]\n",
"\n",
" Personal Lessons:\n",
" - [Growth and self-awareness]\n",
"\n",
" Other People Observations:\n",
" - [Team and interpersonal insights]\n",
"\n",
" Professional Connection:\n",
" - [Direct firefighting career relevance]\"\"\"\n",
"\n",
" def get_next_question(state: PracticeState) -> dict:\n",
" \"\"\"Generates the next practice question\"\"\"\n",
" # Retrieve relevant context\n",
" resume_context = resume_retriever.invoke(state.theme)\n",
" questions_context = questions_retriever.invoke(state.theme)\n",
" \n",
" # Format conversation history\n",
" conversation_history = \"\\n\".join([\n",
" f\"Q: {state.messages[i].content}\\nA: {state.messages[i+1].content}\"\n",
" for i in range(0, len(state.messages)-1, 2)\n",
" if i+1 < len(state.messages)\n",
" ])\n",
"\n",
" # Generate question\n",
" response = model.invoke({\n",
" \"messages\": [\n",
" HumanMessage(content=QUESTION_PROMPT.format(\n",
" theme=state.theme,\n",
" resume_context=resume_context,\n",
" questions_context=questions_context,\n",
" conversation_history=conversation_history\n",
" ))\n",
" ]\n",
" })\n",
" \n",
" return {\"messages\": state.messages + [AIMessage(content=response.content)]}\n",
"\n",
" def process_response(state: PracticeState) -> dict:\n",
" \"\"\"Processes user's response and determines next steps\"\"\"\n",
" # Track the response\n",
" state.gathered_responses.append(state.messages[-1].content)\n",
" state.questions_asked += 1\n",
" \n",
" # Determine if ready for STARTPOP\n",
" ready_for_startpop = state.questions_asked >= 3\n",
" \n",
" return {\n",
" \"messages\": state.messages,\n",
" \"questions_asked\": state.questions_asked,\n",
" \"gathered_responses\": state.gathered_responses,\n",
" \"ready_for_startpop\": ready_for_startpop\n",
" }\n",
"\n",
" def generate_startpop(state: PracticeState) -> dict:\n",
" \"\"\"Generates final STARTPOP response\"\"\"\n",
" # Get final context\n",
" resume_context = resume_retriever.invoke(state.theme)\n",
" \n",
" # Generate STARTPOP\n",
" response = model.invoke({\n",
" \"messages\": [\n",
" HumanMessage(content=STARTPOP_PROMPT.format(\n",
" theme=state.theme,\n",
" responses=\"\\n\".join(state.gathered_responses),\n",
" resume_context=resume_context\n",
" ))\n",
" ]\n",
" })\n",
" \n",
" return {\n",
" \"messages\": state.messages + [AIMessage(content=response.content)],\n",
" \"ready_for_startpop\": True\n",
" }\n",
"\n",
" def should_continue(state: PracticeState) -> str:\n",
" \"\"\"Determines whether to continue questions or generate STARTPOP\"\"\"\n",
" if state.ready_for_startpop:\n",
" return \"generate_startpop\"\n",
" return \"continue_questions\"\n",
"\n",
" # Create workflow\n",
" workflow = StateGraph(PracticeState)\n",
" \n",
" # Add nodes\n",
" # Create workflow\n",
"\n",
"\n",
"# Add nodes\n",
" workflow.add_node(\"get_next_question\", get_next_question)\n",
" workflow.add_node(\"process_response\", process_response)\n",
" workflow.add_node(\"should_continue\", should_continue)\n",
" workflow.add_node(\"generate_startpop\", generate_startpop)\n",
"\n",
" # Add edges\n",
" workflow.add_edge(\"should_continue\", \"continue_questions\", \"continue_questions\")\n",
" workflow.add_edge(\"should_continue\", \"generate_startpop\", \"generate_startpop\")\n",
" workflow.add_edge(\"get_next_question\", \"process_response\", \"process_response\")\n",
" workflow.add_edge(\"process_response\", \"should_continue\", \"should_continue\")\n",
" workflow.add_edge(\"generate_startpop\", END, \"generate_startpop\")\n",
" \n",
" return workflow.compile()\n",
"\n",
"def run_theme_practice(theme: str, resume_retriever, questions_retriever):\n",
" \"\"\"Runs a practice session for a specific theme\"\"\"\n",
" \n",
" practice_bot = create_practice_assistant(theme, resume_retriever, questions_retriever)\n",
" \n",
" # Initialize state\n",
" initial_state = PracticeState(\n",
" messages=[\n",
" SystemMessage(content=f\"Starting practice session for theme: {theme}\"),\n",
" HumanMessage(content=\"I'm ready to practice this theme.\")\n",
" ],\n",
" theme=theme\n",
" )\n",
" \n",
" return practice_bot.stream(initial_state)\n",
"\n",
"# Example usage\n",
"if __name__ == \"__main__\":\n",
" theme = \"Customer Service\"\n",
" \n",
" print(f\"\\nStarting practice session for theme: {theme}\")\n",
" print(\"I'll ask you several questions, then help create a STARTPOP response.\")\n",
" print(\"Type your responses when prompted, or 'quit' to end.\\n\")\n",
" \n",
" for state in run_theme_practice(theme, resume_retriever, questions_retriever):\n",
" if isinstance(state.messages[-1], AIMessage):\n",
" print(\"\\nAssistant:\", state.messages[-1].content)\n",
" \n",
" if not state.ready_for_startpop:\n",
" print(\"\\nYour response:\")\n",
" user_input = input(\"> \")\n",
" if user_input.lower() == 'quit':\n",
" break\n",
" state.messages.append(HumanMessage(content=user_input))\n",
" \n",
" if state.ready_for_startpop and len(state.messages) > 0:\n",
" print(\"\\nPractice complete! Here's your STARTPOP response for this theme.\")"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": []
},
{
"cell_type": "code",
"execution_count": 4,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"[{'id': 1,\n",
" 'theme': 'Disability Questions',\n",
" 'context': \"Firefighters respond to lots of medical calls, many of which involve visible and invisible disabilities.\\n- It's critical to be aware of the unique needs of people with physical health issues and mental health challenges.\\n- Firefighters must provide compassionate care to everyone and giving respect to all regardless of their abilities.\\n- As first responders, firefighters are often the first point of contact for vulnerable individuals, and how they interact can make a lasting impact on the persons well-being.\\n- Firefighters should be well-trained to recognize different disabilities and adapt their approach to ensure effective communication and assistance, especially for those with cognitive or sensory impairments.\\n- This requires empathy, patience, and a strong understanding of mental health and physical disabilities, along with the proper use of equipment and techniques to ensure safety and dignity for everyone involved.\\n- Potential Conclusions:\\no I know that ______ Fire has a strong reputation for responding with compassion and professionalism to individuals with disabilities, ensuring that they feel respected and supported during emergencies.\\no I admire the commitment that ______ Fire has shown in ensuring firefighters are trained to work with all members of the community, including those with both visible and invisible disabilities.\\no I've seen firsthand how important it is for firefighters to provide inclusive care during medical emergencies. I would be honored to join ______ Fire in continuing to up\"},\n",
" {'id': 2,\n",
" 'theme': 'Leadership Skills Questions',\n",
" 'context': \"Leadership is not about having authority; it's about inspiring others to reach their full potential.\\n- Effective leaders lead by example, demonstrating integrity, accountability, and a commitment to teamwork.\\n- In the fire service, leadership is not confined to rank; every firefighter has the opportunity to lead and contribute to the success of the team.\\n- Adaptability and decisiveness are crucial qualities in leadership, especially in high-stress and rapidly changing environments.\\n- Leadership is also about fostering a culture of continuous learning and improvement, encouraging feedback, and promoting innovation.\\n- Potential Conclusions:\\no I've heard about the emphasis on leadership development within ______ Fire, and it's clear that the department values cultivating leaders at all levels. I'm eager to contribute to that culture and continue growing as a leader.\\no During my station visit, I observed how firefighters at ______ Fire take initiative and support each other, regardless of rank. That collaborative leadership approach is something I aspire to emulate and contribute to.\\no I've learned that leadership in the fire service is not just about giving orders; it's about empowering others, building trust, and fostering a sense of unity within the team. I'm excited about the opportunity to lead by example and positively influence my fellow firefighters at ______ Fire.\"},\n",
" {'id': 3,\n",
" 'theme': 'Conflict Questions',\n",
" 'context': 'Conflict is a huge problem in high performing teams.\\n- Creates a poisonous work environment, reduces efficiencies, and creates mental health issues.\\n- Those are serious issues and must be addressed as soon as they pop up.\\n- One of the best ways to address it through increasing the communication and giving people an opportunity to explain their opinions or viewpoints.\\n- I tend to think about the three Ts (teamwork, training and trust) and how important it is to fall back on those.\\n- Attempt to secure behaviour modification through voluntary compliance.\\n- Potential Conclusions:\\no I know that professionalism runs through the entire department here. ______\\no Firefighters are professional and committed to safe and respectful workplaces.\\no One thing about the fire service is that you all do a great job of communicating and creating a chain of command to help simplify complex problems\\no Its important to remember the values of the fire service and keep those in mind whenever conflicts arise.\\no Tie in stats and figures from your research on the department.'},\n",
" {'id': 4,\n",
" 'theme': 'Stress Questions',\n",
" 'context': 'My big takeaway is that stress is everywhere, and it affects everyone in different ways.\\n- The amount of mental health issues and stress levels are up exponentially with the community.\\n- Especially when you factor in the effects of COVID-19 and the lockdowns.\\n- That _________ situation made me realize that we must be supportive of one another and reduce the stigma.\\n- Potential Conclusions:\\no I know that the team members at _______ Fire are exposed to stressful situations on a regular basis, and it is critical that they be supportive to one another in order to maintain a strong team.\\no I have spoken to ______ about your mental health programs and can see that you really take the time to pour into each of your firefighters cup. I really admire that.\\no I looked into that _________ program that your department us'},\n",
" {'id': 5,\n",
" 'theme': 'Emergency Questions',\n",
" 'context': 'Emergencies can happen anywhere at anytime.\\n- Usually with little to no warning.\\n- During those times people fall back onto their training and most commonly practiced strategies.\\n- We need to ensure that our personnel are available and ready to answer the call whenever that happens in the community, and they are using the most effective strategies and techniques possible.\\n- Potential Conclusions:\\no I know that the expectation of _______ Fire is to train at least 2-3 hours per shift.\\no That works out to 14-21 hours per month. When you factor in running calls in between those training sessions there is a fair bit of opportunity for Firefighters to become very good at their jobs and be fully prepared.\\no Consistent commitment to training everything from the basics up to the complicated things 2-3 hours per shift is what makes the people on _____ Fire so good at their job.'},\n",
" {'id': 6,\n",
" 'theme': 'Mistake',\n",
" 'context': 'We all make mistakes. It is okay to make them. But it is not okay to not learn from them.\\n- Mistakes are just proof that you are trying your best.\\n- They are an opportunity for growth and for development.\\n- They are the things that help sharpen the knives in a drawer.\\n- The key is not to make the same mistake twice.\\n- Potential Conclusions:\\no I am certain that _______ Firefighters conduct regular follow-ups after calls.\\no Its important for everyone to check their ego and be accountable for the things they messed up on.\\no I know that Chief ______ promotes an open and transparent environment. He/She is not afraid to admit when they made a mistake. So, it is important for everyone in the department to follow suit.'},\n",
" {'id': 7,\n",
" 'theme': 'Cultural, Diversity, and Inclusion Questions',\n",
" 'context': 'Communities are becoming more and more diverse everyday. It is important for the Fire Service to recognize that.\\n- Steps can be taken every single day to create an environment that is inclusive and open to everyone regardless of their background, language, abilities, or self-identification.\\n- Public servants serve the public.\\n- No passing judgement on people. No racism, no homophobia, no misogyny.\\n- Treat everyone with respect and educate ourselves about the differences in our communities.\\n- Potential Conclusions:\\no ______ Fire is very professional and respectful. I have only seen and heard good things about how much of a concerted effort you are making to be more inclusive.\\no I spent some time looking at the Public Education pamphlets at station _____ and saw that they were offered in a bunch of different languages. That was amazing and I really think that shows the community how much you care about reducing the barriers to safety.\\no I spoke with _____ and learned about how enjoyable of an experience they have had working on your departmen'},\n",
" {'id': 8,\n",
" 'theme': 'Customer Service Questions',\n",
" 'context': 'Providing great customer service really just requires caring about people and trying to always make things better than you found it.\\n- Our communities are better served when they have people that are willing to sacrifice their time and energy.\\n- I personally enjoy going to places and working with people that provide great customer service. I would only expect that to be the level of service provided by firefighters.\\n- Potential Conclusions:\\no You cant train people to care and its important for the fire service to hire people who innately have a desire to go the extra mile. It has to be in their DNA.\\no I know that _____ Fire has done a great job finding lots of those types of people and they constantly work towards fostering that characteristic in everyone brought into the organization.\\no Firefighters go above and beyond every shift. Its our job to serve the community and protect life, property'},\n",
" {'id': 9,\n",
" 'theme': 'Successful and Unsuccessful Team Questions',\n",
" 'context': 'Teamwork is necessary to assist in overcoming emergencies. Especially expanding ones. I understand how chain of commands works and the importance of monitoring the span of control as well.\\n- Great teamwork creates synergy in the workplace and makes environments happier, healthier, and safer.\\n- There is no “I” in team.\\n- All tasks are important no matter how big or small it may seem.\\n- Great teams are built by people that are committed to training and knowing their roles well.\\n- Need to train in order to create muscle memory and prevent “skills fade”\\n- Potential Conclusions:\\no I know that Firefighting is a team sport and that _____ Fire does a great job in fostering that camaraderie.\\no I have seen the _____ Fire team play in _____ tournament and know that you guys applaud crews bonding over meals at the station.\\no I really appreciate the fact that you allow crews to train together and share insights learned across the department so that everyone gets better all the time.\\no Include stats and figures, following SOPs and safety protocols into the answer'},\n",
" {'id': 10,\n",
" 'theme': 'Disagree with a Supervisor Questions',\n",
" 'context': 'Disagreements can and will happen but what matters is that the issues are addressed in a respectful and professional manner.\\n- I always recommend doing them in a private and non-confrontational manner\\n- With a focus on finding acceptable solutions that can be implemented effectively.\\n- The idea is to not let things linger and harbour because that creates a poisonous work environment.\\n- Potential Conclusions:\\no I understand my role in the chain of command and will always try my best to follow orders as they are given. But whenever a disagreement may come up it is important to show respect and listen to all sides.\\no _____ Fire works hard to promote captains and chiefs that are smart, capable and proven leaders. It is important to acknowledge that every time there is a potential disagreement. They may see things that I am not aware of.\\no _____ Fire works hard to minimize the number of disagreements in the workplace.'},\n",
" {'id': 11,\n",
" 'theme': 'Rule Bending',\n",
" 'context': 'I do not bend rules that jeopardize health and safety or rules that test my ethics and morality.\\n- I know that the fire service has that same perspective.\\n- Therefore, all organizations need to have rules and all people in those organizations need to know them.\\n- This is why there are internal SOPs, OHSA, HTA, Fire Code, Criminal Code etc.\\n- Potential Conclusions:\\no I know that _____ Fire has a robust SOP package, and it is part of the training process for every new hire to go through them and get schooled up on the importance of them.\\no The onus is on me to spend time learning the ins and outs of this organization if I am blessed with the opportunity to work here.\\no Firefighters need to be rule followers. It is an inherently dangerous job and freelancing has no part o.'},\n",
" {'id': 12,\n",
" 'theme': 'Integrity Challenge Questions',\n",
" 'context': 'Integrity is the cornerstone of the fire service profession, guiding every action and decision.\\n- Firefighters are entrusted with public safety, making it imperative to uphold the highest ethical standards.\\n- In the fire service, we are governed by regulations such as the NFPA standards and the Ontario FPPA, which mandate strict compliance to ensure safety and well-being.\\n- These guidelines underscore the need for transparency and ethical conduct in all our actions.\\n- Potential Conclusions:\\no Integrity is not just a personal attribute; it is a professional necessity that ensures the effectiveness and reliability of our fire service operations.\\no When faced with an integrity challenge, it is essential to remain steadfast in ethical principles, even under pressure.\\no This experience reinforced my commitment to the values of the fire service and highlighted the importance of fostering a culture where integrity is paramount.\\no By upholding these standards, we not only protect ourselves and our colleagues but also maintain the trust and confidence of the communities we serve.'},\n",
" {'id': 13,\n",
" 'theme': 'Taking a Shortcut at work',\n",
" 'context': \"I believe in having strong work ethic. I was raised that way and my work experience to date proves that…\\n- I definitely do not take shortcuts around things that compromise health and safety or my ethics and morality.\\n- I never take shortcuts that compromise the health and safety of myself or others, or that challenge my ethical and moral values.\\n- I believe that the fire service shares this same perspective, prioritizing safety, ethics, and morality above all else.\\n- In my view, all organizations should establish clear rules, and it is essential for every member of those organizations to be aware of and follow these rules.\\n- This is why organizations have internal Standard Operating Procedures (SOPs), Occupational Health and Safety Act (OHSA) guidelines, Highway Traffic Act (HTA) regulations, Fire Codes, and even the Criminal Code when necessary.\\n- Potential Conclusions:\\no I'm aware that at _____ Fire, they have a comprehensive set of Standard Operating Procedures (SOPs) that are diligently followed. During my training, I learned about the critical importance of these procedures and the reasons for adhering to them.\\no If I were fortunate enough to join this organization, I understand that it would be my responsibility to thoroughly acquaint myself with its rules and procedures. I'm committed to investing the necessary time and effort to ensure I comply with them.\\no In firefighting, there's no room for shortcuts. It's an inherently perilous job and deviating from established procedures can jeopardize lives. Rules are not just guidelines but safeguards that protect everyone and ensure a safe return from each mission.\"},\n",
" {'id': 14,\n",
" 'theme': 'Delivering Difficult Messages',\n",
" 'context': \"I do not shy away from the responsibility of delivering difficult messages when necessary, even though it may be uncomfortable. My commitment to honesty and ethical conduct remains unwavering.\\n- I believe that the fire service, like any responsible organization, understands the importance of addressing challenging issues head-on, which aligns with my perspective on this matter.\\n- In all organizations, there should be clear protocols and guidelines for delivering difficult messages effectively and sensitively, ensuring that the message is conveyed while respecting the dignity and feelings of the recipients.\\n- This is why organizations often have established procedures and communication guidelines to handle such situations professionally and ethically.\\n- Potential Conclusions:\\no I'm aware that at _____ Fire, they prioritize open and honest communication. During my training, I learned about their approach to delivering difficult messages and the importance of doing so with empathy and professionalism.\\no If I were part of this organization, I would understand that delivering difficult messages might be a part of my role. I would be committed to following their established protocols and guidelines for addressing such situations.\\no In firefighting and similar high-stakes professions, effective communication, even in challenging circumstances, can be a matter of life and death. The rules and procedures in place are not just about following a script but ensuring that messages are conveyed in a way that respects the emotions and well-being of all involved parties.\"},\n",
" {'id': 15,\n",
" 'theme': 'Not Following SOPs/SOGs',\n",
" 'context': \"I have never deviated from established SOPs at work, as doing so can compromise safety, ethical standards, and the integrity of the organization.\\n- I understand that the fire service, like any responsible organization, places a high value on adherence to SOPs, which is consistent with my perspective.\\n- In every organization, it's crucial to have clear and well-documented SOPs that every member understands and follows. This ensures consistency, safety, and ethical conduct.\\n- This is why organizations implement internal SOPs and adhere to external regulations like OHSA, HTA, and Fire Codes to maintain high standards of operation.\\n- Potential conclusions:\\no I'm aware that at _____ Fire, strict adherence to SOPs is fundamental to their operational success. During my training, I gained a deep appreciation for the importance of following these procedures and the consequences of not doing so.\\no If I were to become part of this organization, I would fully understand the gravity of following SOPs. I would uphold these standards and would actively seek training and support to ensure compliance.\\no In firefighting and similar high-risk professions, disregarding SOPs is simply not an option. These procedures are in place to protect lives and property. Any deviation can have serious consequences, and rule adherence is non-negotiable.\"},\n",
" {'id': 16,\n",
" 'theme': 'Continuous Improvement',\n",
" 'context': \"Continuous improvement is about striving to be better every day, both as an individual and as part of a team.\\n- I believe that the fire service embodies this concept by constantly evolving through training, adopting new technologies, and learning from past experiences.\\n- Reflecting on one's performance and seeking feedback are essential components of continuous improvement, as they help identify strengths and areas for growth.\\n- Staying updated with new firefighting techniques, equipment, and regulations is crucial for maintaining effectiveness and safety in the field.\\n- Potential Conclusions:\\no I've seen how ______ Fire prioritizes ongoing training and professional development to ensure its firefighters remain at the forefront of the profession. I look forward to being part of an organization that values growth and innovation.\\no During my station visit, I was impressed by the emphasis on learning and improvement at ______ Fire. That environment aligns perfectly with my personal commitment to always better myself and support my team in doing the same.\\no I believe continuous improvement is not just about improving skills but also about fostering a culture where everyone strives to do better. At ______ Fire, Im eager to contribute to that culture by embracing challenges, seeking feedback, and pursuing opportunities for growth.\"},\n",
" {'id': 17,\n",
" 'theme': 'Handling Sensitive Information',\n",
" 'context': 'Firefighters are often entrusted with sensitive information, whether it pertains to medical calls, emergency incidents, or personal details about community members.\\n- Maintaining confidentiality and discretion is critical for preserving trust and ensuring the dignity of individuals involved.\\n- Handling sensitive information responsibly requires understanding and adhering to organizational policies, as well as exercising sound judgment.\\n- Respecting privacy is a key component of professionalism, especially in a role as visible and impactful as firefighting.\\n- Potential Conclusions:\\no I understand that ______ Fire has clear guidelines and training around handling sensitive information. I respect and appreciate the importance of these protocols and would adhere to them without compromise.\\no If given the opportunity to join ______ Fire, I would uphold the highest standards of confidentiality and discretion, ensuring that sensitive information is treated with the respect it deserves.\\no Handling sensitive information with care is essential to maintaining the trust of the community and the integrity of the fire service. Im committed to embodying these values and ensuring that all information is managed professionally and ethically.'},\n",
" {'id': 18,\n",
" 'theme': 'Solving a Problem',\n",
" 'context': \"I believe problem-solving is one of the most valuable skills in the fire service, as it often determines the success or failure of a critical situation.\\n- Effective problem-solving requires a clear assessment of the situation, evaluating available resources, and making informed decisions quickly.\\n- Firefighting often involves scenarios where unexpected challenges arise, and the ability to stay calm and address issues methodically is essential.\\n- Collaboration is a significant part of problem-solving, as no one firefighter has all the answers. Solutions come from teamwork and leveraging everyone's strengths.\\n- Potential Conclusions:\\no I understand that ______ Fire emphasizes critical thinking and problem-solving in their training programs. During my training, I honed these skills and learned how to approach challenges systematically and effectively.\\no If I were part of ______ Fire, I would actively apply my problem-solving abilities in both emergency and non-emergency situations, ensuring I work collaboratively with my team to find the best outcomes.\\no Solving problems in firefighting goes beyond emergencies; it's about addressing challenges proactively, whether it's equipment maintenance, community outreach, or operational efficiency. I'm committed to contributing to this problem-solving culture at ______ Fire.\"},\n",
" {'id': 19,\n",
" 'theme': 'Challenge Questions',\n",
" 'context': 'Life is full of challenges. It is important for firefighters to be the type of people that take those challenges head on and constantly work to find ways to overcome them.\\n- Grit, persistence, creative problem solving, and strong mental health are the keys to overcoming challenges.\\n- Life can change in a second. Its important to be adaptive and flexible.\\n- Potential Conclusions:\\no And I am certain that ______ Fire works very hard to meet every challenge and then overcome them.\\no I think about how you guys handled the ________ situation\\no or the recent fire at _______\\no and as an outsider looking in, I was thoroughly impressed with the way the department handled it.'}]"
]
},
"execution_count": 4,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"themes"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": []
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"from typing import List, Dict\n",
"from pydantic import BaseModel, Field\n",
"from langchain_core.messages import BaseMessage, HumanMessage, AIMessage, SystemMessage\n",
"from langchain_openai import ChatOpenAI\n",
"from langchain_core.prompts import ChatPromptTemplate\n",
"from langgraph.graph import StateGraph, END\n",
"\n",
"class PracticeState(BaseModel):\n",
" \"\"\"Tracks the state of the practice session\"\"\"\n",
" messages: List[BaseMessage] = Field(default_factory=list)\n",
" theme: str\n",
" questions_asked: int = 0\n",
" gathered_responses: List[str] = Field(default_factory=list)\n",
" ready_for_startpop: bool = False\n",
"\n",
"def create_practice_assistant(theme: str, resume_retriever, questions_retriever):\n",
" \"\"\"Creates a practice assistant for a specific interview theme\"\"\"\n",
" \n",
" model = ChatOpenAI(temperature=0.7, model=\"gpt-4-turbo-preview\")\n",
"\n",
" # Core system prompt for question generation\n",
" QUESTION_PROMPT = \"\"\"You are an AI assistant helping prepare for a firefighter interview, focusing on the theme: {theme}.\n",
"\n",
" Resume Context:\n",
" {resume_context}\n",
"\n",
" Sample Questions for this Theme:\n",
" {questions_context}\n",
"\n",
" Previous Questions and Responses:\n",
" {conversation_history}\n",
"\n",
" Generate a focused question that:\n",
" 1. Relates to the candidate's background from their resume\n",
" 2. Aligns with the current theme\n",
" 3. Encourages STAR/STARTPOP format responses\n",
" 4. Builds on previous responses\n",
" 5. Helps gather material for a strong STARTPOP response\n",
"\n",
" Ask only ONE question and make it conversational and encouraging.\"\"\"\n",
"\n",
" # STARTPOP generation prompt\n",
" STARTPOP_PROMPT = \"\"\"Based on all the responses gathered during our practice session, let's create a strong STARTPOP response for the theme: {theme}\n",
"\n",
" Theme: {theme}\n",
" Collected Responses: {responses}\n",
" Resume Context: {resume_context}\n",
"\n",
" Create a polished STARTPOP response that:\n",
" 1. Uses the best examples from the practice session\n",
" 2. Incorporates relevant experience from the resume\n",
" 3. Follows the exact STARTPOP format:\n",
"\n",
" Situation:\n",
" - [Specific context and background]\n",
"\n",
" Task:\n",
" - [Clear objectives and responsibilities]\n",
"\n",
" Action:\n",
" - [Both potential negative approaches and chosen positive actions]\n",
"\n",
" Results:\n",
" - [Concrete outcomes with timeframes]\n",
"\n",
" Transitions:\n",
" - [Professional firefighting terminology]\n",
"\n",
" Personal Lessons:\n",
" - [Growth and self-awareness]\n",
"\n",
" Other People Observations:\n",
" - [Team and interpersonal insights]\n",
"\n",
" Professional Connection:\n",
" - [Direct firefighting career relevance]\"\"\"\n",
"\n",
" def get_next_question(state: PracticeState) -> dict:\n",
" \"\"\"Generates the next practice question\"\"\"\n",
" # Retrieve relevant context\n",
" resume_context = resume_retriever.invoke(state.theme)\n",
" questions_context = questions_retriever.invoke(state.theme)\n",
" \n",
" # Format conversation history\n",
" conversation_history = \"\\n\".join([\n",
" f\"Q: {state.messages[i].content}\\nA: {state.messages[i+1].content}\"\n",
" for i in range(0, len(state.messages)-1, 2)\n",
" if i+1 < len(state.messages)\n",
" ])\n",
"\n",
" # Generate question\n",
" chain = ChatPromptTemplate.from_template(QUESTION_PROMPT) | model\n",
" \n",
" response = chain.invoke({\n",
" \"theme\": state.theme,\n",
" \"resume_context\": resume_context,\n",
" \"questions_context\": questions_context,\n",
" \"conversation_history\": conversation_history\n",
" })\n",
" \n",
" return {\"messages\": state.messages + [AIMessage(content=response)]}\n",
"\n",
" def process_response(state: PracticeState) -> dict:\n",
" \"\"\"Processes user's response and determines next steps\"\"\"\n",
" # Track the response\n",
" state.gathered_responses.append(state.messages[-1].content)\n",
" state.questions_asked += 1\n",
" \n",
" # Determine if ready for STARTPOP\n",
" ready_for_startpop = state.questions_asked >= 3\n",
" \n",
" return {\n",
" \"messages\": state.messages,\n",
" \"questions_asked\": state.questions_asked,\n",
" \"gathered_responses\": state.gathered_responses,\n",
" \"ready_for_startpop\": ready_for_startpop\n",
" }\n",
"\n",
" def generate_startpop(state: PracticeState) -> dict:\n",
" \"\"\"Generates final STARTPOP response\"\"\"\n",
" # Get final context\n",
" resume_context = resume_retriever.invoke(state.theme)\n",
" \n",
" # Generate STARTPOP\n",
" chain = ChatPromptTemplate.from_template(STARTPOP_PROMPT) | model\n",
" \n",
" response = chain.invoke({\n",
" \"theme\": state.theme,\n",
" \"responses\": \"\\n\".join(state.gathered_responses),\n",
" \"resume_context\": resume_context\n",
" })\n",
" \n",
" return {\n",
" \"messages\": state.messages + [AIMessage(content=response)],\n",
" \"ready_for_startpop\": True\n",
" }\n",
"\n",
" def should_continue(state: PracticeState) -> str:\n",
" \"\"\"Determines whether to continue questions or generate STARTPOP\"\"\"\n",
" if state.ready_for_startpop:\n",
" return \"generate_startpop\"\n",
" return \"continue_questions\"\n",
"\n",
" # Create workflow\n",
" workflow = StateGraph(PracticeState)\n",
" \n",
" # Add nodes\n",
" workflow.add_node(\"get_next_question\", get_next_question)\n",
" workflow.add_node(\"process_response\", process_response)\n",
" workflow.add_node(\"should_continue\", should_continue)\n",
" workflow.add_node(\"generate_startpop\", generate_startpop)\n",
" \n",
" # Add edges\n",
" workflow.add_edge(\"should_continue\", \"continue_questions\", \"get_next_question\")\n",
" workflow.add_edge(\"should_continue\", \"generate_startpop\", \"generate_startpop\")\n",
" workflow.add_edge(\"get_next_question\", \"process_response\")\n",
" workflow.add_edge(\"process_response\", \"should_continue\")\n",
" workflow.add_edge(\"generate_startpop\", END)\n",
" \n",
" return workflow.compile()\n",
"\n",
"def run_theme_practice(theme: str, resume_retriever, questions_retriever):\n",
" \"\"\"Runs a practice session for a specific theme\"\"\"\n",
" \n",
" practice_bot = create_practice_assistant(theme, resume_retriever, questions_retriever)\n",
" \n",
" # Initialize state\n",
" initial_state = PracticeState(\n",
" messages=[\n",
" SystemMessage(content=f\"Starting practice session for theme: {theme}\"),\n",
" HumanMessage(content=\"I'm ready to practice this theme.\")\n",
" ],\n",
" theme=theme\n",
" )\n",
" \n",
" return practice_bot.stream(initial_state)\n",
"\n",
"# Example usage\n",
"if __name__ == \"__main__\":\n",
" theme = \"Customer Service\"\n",
" \n",
" print(f\"\\nStarting practice session for theme: {theme}\")\n",
" print(\"I'll ask you several questions, then help create a STARTPOP response.\")\n",
" print(\"Type your responses when prompted, or 'quit' to end.\\n\")\n",
" \n",
" for state in run_theme_practice(theme, resume_retriever, questions_retriever):\n",
" if isinstance(state.messages[-1], AIMessage):\n",
" print(\"\\nAssistant:\", state.messages[-1].content)\n",
" \n",
" if not state.ready_for_startpop:\n",
" print(\"\\nYour response:\")\n",
" user_input = input(\"> \")\n",
" if user_input.lower() == 'quit':\n",
" break\n",
" state.messages.append(HumanMessage(content=user_input))\n",
" \n",
" if state.ready_for_startpop and len(state.messages) > 0:\n",
" print(\"\\nPractice complete! Here's your STARTPOP response for this theme.\")"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### START POP AGENT"
]
},
{
"cell_type": "code",
"execution_count": 2,
"metadata": {},
"outputs": [],
"source": [
"import getpass\n",
"import os\n",
"\n",
"if not os.environ.get(\"OPENAI_API_KEY\"):\n",
" os.environ[\"OPENAI_API_KEY\"] = getpass.getpass(\"Enter API key for OpenAI: \")\n",
"\n",
"from langchain_openai import ChatOpenAI\n",
"\n",
"llm = ChatOpenAI(model=\"gpt-4o-mini\")\n",
"\n",
"\n",
"import getpass\n",
"import os\n",
"\n",
"if not os.environ.get(\"OPENAI_API_KEY\"):\n",
" os.environ[\"OPENAI_API_KEY\"] = getpass.getpass(\"Enter API key for OpenAI: \")\n",
"\n",
"from langchain_openai import OpenAIEmbeddings\n",
"\n",
"embeddings = OpenAIEmbeddings(model=\"text-embedding-3-large\")\n",
"\n"
]
},
{
"cell_type": "code",
"execution_count": 9,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"\n",
"\u001b[1m[\u001b[0m\u001b[34;49mnotice\u001b[0m\u001b[1;39;49m]\u001b[0m\u001b[39;49m A new release of pip is available: \u001b[0m\u001b[31;49m23.0.1\u001b[0m\u001b[39;49m -> \u001b[0m\u001b[32;49m24.3.1\u001b[0m\n",
"\u001b[1m[\u001b[0m\u001b[34;49mnotice\u001b[0m\u001b[1;39;49m]\u001b[0m\u001b[39;49m To update, run: \u001b[0m\u001b[32;49mpip install --upgrade pip\u001b[0m\n",
"Note: you may need to restart the kernel to use updated packages.\n"
]
}
],
"source": [
"pip install -qU langchain-core"
]
},
{
"cell_type": "code",
"execution_count": 3,
"metadata": {},
"outputs": [],
"source": [
"from langchain_core.vectorstores import InMemoryVectorStore\n",
"\n",
"vector_store = InMemoryVectorStore(embeddings)"
]
},
{
"cell_type": "code",
"execution_count": 14,
"metadata": {},
"outputs": [],
"source": [
"from langchain_community.document_loaders import WebBaseLoader\n",
"from langchain_community.vectorstores import FAISS\n",
"from langchain_openai import OpenAIEmbeddings\n",
"from langchain_text_splitters import RecursiveCharacterTextSplitter\n",
"from langchain.schema import Document\n",
"import json\n",
"import os\n",
"\n",
"# Load questions and themes\n",
"question_path = \"../data/config_files/questions.json\"\n",
"theme_path = \"../data/config_files/theme_context.json\"\n",
"with open(question_path, \"r\") as f:\n",
" questions = json.load(f)\n",
"\n",
"with open(theme_path, \"r\") as f:\n",
" themes = json.load(f)\n",
"\n",
"def load_document(file_path: str):\n",
" extension = os.path.splitext(file_path)[1].lower()\n",
" \n",
" if extension in ['.doc', '.docx']:\n",
" # Convert .doc or .docx to PDF first\n",
" pdf_path = convert_word_to_pdf(file_path)\n",
" loader = PyPDFLoader(pdf_path)\n",
" elif extension == '.pdf':\n",
" loader = PyPDFLoader(file_path)\n",
" else:\n",
" raise ValueError(f\"Unsupported file type: {extension}. Only .pdf, .docx, and .doc are supported.\")\n",
" \n",
" return loader.load()\n",
"\n",
"# Create text splitter\n",
"text_splitter = RecursiveCharacterTextSplitter.from_tiktoken_encoder(\n",
" chunk_size=100, chunk_overlap=50\n",
")\n",
"\n",
"# Load and split resume document\n",
"docs = load_document('../upload_folder/Resume_-_Erika_Kiviaho.pdf')\n",
"resume_splits = text_splitter.split_documents(docs)\n",
"\n",
"\n",
"# Prepare questions for vectorDB - Convert dictionary to Document objects\n",
"questions_docs = [\n",
" Document(\n",
" page_content=str(value),\n",
" metadata={\"question_id\": key}\n",
" )\n",
" for key, value in questions.items()\n",
"]\n",
"questions_splits = text_splitter.split_documents(questions_docs)\n",
"\n"
]
},
{
"cell_type": "code",
"execution_count": 11,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"[Document(metadata={'question_id': 'General Competency Questions'}, page_content=\"[{'id': 1, 'question': 'Why do you want to be a firefighter?'}, {'id': 2, 'question': 'What have you done to prepare for a career in the Fire Service?'}, {'id': 3, 'question': 'Why do you want to work for this department?'}, {'id': 4, 'question': 'Name some of the traits, characteristics, or attributes of a good firefighter.'}, {'id': 5,\"),\n",
" Document(metadata={'question_id': 'General Competency Questions'}, page_content=\"3, 'question': 'Why do you want to work for this department?'}, {'id': 4, 'question': 'Name some of the traits, characteristics, or attributes of a good firefighter.'}, {'id': 5, 'question': 'What are some of the biggest challenges faced by the Fire Service today?'}, {'id': 6, 'question': 'Describe the emergency vs. non-emergency duties of a firefighter.'}, {'id': 7,\"),\n",
" Document(metadata={'question_id': 'General Competency Questions'}, page_content=\"'What are some of the biggest challenges faced by the Fire Service today?'}, {'id': 6, 'question': 'Describe the emergency vs. non-emergency duties of a firefighter.'}, {'id': 7, 'question': 'Where do you see yourself in 1, 5, 10, 20 years?'}, {'id': 8, 'question': 'Describe the chain of command and your role in it.'}, {'id': 9, 'question':\"),\n",
" Document(metadata={'question_id': 'General Competency Questions'}, page_content=\"'Where do you see yourself in 1, 5, 10, 20 years?'}, {'id': 8, 'question': 'Describe the chain of command and your role in it.'}, {'id': 9, 'question': 'How do you handle stress, now and once you have the job?'}, {'id': 10, 'question': 'How do you think the role of the firefighter will be different in 5 years?'}, {'id': 11,\"),\n",
" Document(metadata={'question_id': 'General Competency Questions'}, page_content=\"'How do you handle stress, now and once you have the job?'}, {'id': 10, 'question': 'How do you think the role of the firefighter will be different in 5 years?'}, {'id': 11, 'question': 'What is the organizational structure of our Fire Department?'}, {'id': 12, 'question': 'Why do you think honesty and integrity are important in the Fire Service?'}, {'id': 13, 'question': 'What\"),\n",
" Document(metadata={'question_id': 'General Competency Questions'}, page_content=\"'What is the organizational structure of our Fire Department?'}, {'id': 12, 'question': 'Why do you think honesty and integrity are important in the Fire Service?'}, {'id': 13, 'question': 'What are the advantages and disadvantages of similar vs diverse teams?'}, {'id': 14, 'question': 'List in order of importance: Emergency Response, Public Education, Fire Standards/Enforcement.'}, {'id': 15, 'question': 'What\"),\n",
" Document(metadata={'question_id': 'General Competency Questions'}, page_content=\"advantages and disadvantages of similar vs diverse teams?'}, {'id': 14, 'question': 'List in order of importance: Emergency Response, Public Education, Fire Standards/Enforcement.'}, {'id': 15, 'question': 'What is the most important duty of a firefighter?'}, {'id': 16, 'question': 'What does leadership mean to you?'}, {'id': 17, 'question': 'What do you like most and least about a supervisor?'},\"),\n",
" Document(metadata={'question_id': 'General Competency Questions'}, page_content=\"is the most important duty of a firefighter?'}, {'id': 16, 'question': 'What does leadership mean to you?'}, {'id': 17, 'question': 'What do you like most and least about a supervisor?'}, {'id': 18, 'question': 'What do you appreciate in a managers style?'}, {'id': 19, 'question': 'What are the six common leadership styles in the Fire Service?'}, {'id':\"),\n",
" Document(metadata={'question_id': 'General Competency Questions'}, page_content=\"{'id': 18, 'question': 'What do you appreciate in a managers style?'}, {'id': 19, 'question': 'What are the six common leadership styles in the Fire Service?'}, {'id': 20, 'question': 'What do you like most and least about being a firefighter?'}, {'id': 21, 'question': 'How does diversity impact the Fire Service today?'}, {'id': 22, 'question': 'How\"),\n",
" Document(metadata={'question_id': 'General Competency Questions'}, page_content=\"20, 'question': 'What do you like most and least about being a firefighter?'}, {'id': 21, 'question': 'How does diversity impact the Fire Service today?'}, {'id': 22, 'question': 'How would you make a positive impact regarding the diversity in the community?'}, {'id': 23, 'question': 'Firefighters work 24-hour shifts. How have you prepared, and what challenges do you think youll face?'},\"),\n",
" Document(metadata={'question_id': 'General Competency Questions'}, page_content=\"would you make a positive impact regarding the diversity in the community?'}, {'id': 23, 'question': 'Firefighters work 24-hour shifts. How have you prepared, and what challenges do you think youll face?'}, {'id': 24, 'question': 'Public Education is important in the Fire Service. How would you provide this service?'}, {'id': 25, 'question': 'You are a probationary firefighter. How do you prepare\"),\n",
" Document(metadata={'question_id': 'General Competency Questions'}, page_content=\"{'id': 24, 'question': 'Public Education is important in the Fire Service. How would you provide this service?'}, {'id': 25, 'question': 'You are a probationary firefighter. How do you prepare yourself?'}, {'id': 26, 'question': 'Why is respect so important, and what does it mean?'}, {'id': 27, 'question': 'Would you break a rule if asked to?'}, {'id': 28,\"),\n",
" Document(metadata={'question_id': 'General Competency Questions'}, page_content=\"{'id': 26, 'question': 'Why is respect so important, and what does it mean?'}, {'id': 27, 'question': 'Would you break a rule if asked to?'}, {'id': 28, 'question': 'What are potential sources of workplace conflict? How would you handle workplace conflict?'}, {'id': 29, 'question': 'Why should we hire you?'}, {'id': 30, 'question': 'What are your strengths\"),\n",
" Document(metadata={'question_id': 'General Competency Questions'}, page_content=\"'What are potential sources of workplace conflict? How would you handle workplace conflict?'}, {'id': 29, 'question': 'Why should we hire you?'}, {'id': 30, 'question': 'What are your strengths and weaknesses? (What would your boss say about you?)'}, {'id': 31, 'question': 'How do you want to be remembered at the end of your career?'}, {'id': 32, 'question': 'What skills do\"),\n",
" Document(metadata={'question_id': 'General Competency Questions'}, page_content=\"(What would your boss say about you?)'}, {'id': 31, 'question': 'How do you want to be remembered at the end of your career?'}, {'id': 32, 'question': 'What skills do you bring to Dispatch?'}, {'id': 33, 'question': 'Walk me through a truck check.'}, {'id': 34, 'question': 'How do you define teamwork in the context of firefighting?'}, {'id':\"),\n",
" Document(metadata={'question_id': 'General Competency Questions'}, page_content=\"bring to Dispatch?'}, {'id': 33, 'question': 'Walk me through a truck check.'}, {'id': 34, 'question': 'How do you define teamwork in the context of firefighting?'}, {'id': 35, 'question': 'What motivates you to perform well in stressful situations?'}, {'id': 36, 'question': 'Explain how you would handle feedback from a superior, especially if it was critical.'}, {'id':\"),\n",
" Document(metadata={'question_id': 'General Competency Questions'}, page_content=\"35, 'question': 'What motivates you to perform well in stressful situations?'}, {'id': 36, 'question': 'Explain how you would handle feedback from a superior, especially if it was critical.'}, {'id': 37, 'question': 'What is your understanding of the core values of the Fire Service?'}, {'id': 38, 'question': 'Describe a time when you demonstrated initiative in the workplace.'}, {'id': 39,\"),\n",
" Document(metadata={'question_id': 'General Competency Questions'}, page_content=\"37, 'question': 'What is your understanding of the core values of the Fire Service?'}, {'id': 38, 'question': 'Describe a time when you demonstrated initiative in the workplace.'}, {'id': 39, 'question': 'How do you prioritize tasks during an emergency response?'}, {'id': 40, 'question': 'What role does technology play in modern firefighting, and how are you prepared for it?'}, {'id': 41,\"),\n",
" Document(metadata={'question_id': 'General Competency Questions'}, page_content=\"'question': 'How do you prioritize tasks during an emergency response?'}, {'id': 40, 'question': 'What role does technology play in modern firefighting, and how are you prepared for it?'}, {'id': 41, 'question': 'How would you approach learning new skills and techniques required for this job?'}, {'id': 42, 'question': 'Explain how you balance personal and professional commitments in a demanding job.'}, {'id': 43,\"),\n",
" Document(metadata={'question_id': 'General Competency Questions'}, page_content=\"'question': 'How would you approach learning new skills and techniques required for this job?'}, {'id': 42, 'question': 'Explain how you balance personal and professional commitments in a demanding job.'}, {'id': 43, 'question': 'What strategies do you use to ensure continuous improvement in your work?'}, {'id': 44, 'question': 'How do you approach building trust and relationships within a new team?'}, {'id': 45,\"),\n",
" Document(metadata={'question_id': 'General Competency Questions'}, page_content=\"43, 'question': 'What strategies do you use to ensure continuous improvement in your work?'}, {'id': 44, 'question': 'How do you approach building trust and relationships within a new team?'}, {'id': 45, 'question': 'What does a day in the life of a firefighter look like for both emergency and non-emergency activities?'}]\"),\n",
" Document(metadata={'question_id': 'Situational Questions'}, page_content=\"[{'id': 1, 'question': 'What would you do if a firefighter makes disparaging remarks in public about visible minorities?'}, {'id': 2, 'question': 'What would you do if a senior firefighter is making inappropriate, unwelcomed, bullying comments towards another firefighter?'}, {'id': 3, 'question': 'What would you do if you believe that a fellow firefighter is unfit for duty (e.g., drugs, alcohol, medication)?'},\"),\n",
" Document(metadata={'question_id': 'Situational Questions'}, page_content=\"unwelcomed, bullying comments towards another firefighter?'}, {'id': 3, 'question': 'What would you do if you believe that a fellow firefighter is unfit for duty (e.g., drugs, alcohol, medication)?'}, {'id': 4, 'question': 'What would you do if you are following an order from your captain and a more senior officer gives you an alternate order?'}, {'id': 5, 'question': 'What would you do if your\"),\n",
" Document(metadata={'question_id': 'Situational Questions'}, page_content=\"4, 'question': 'What would you do if you are following an order from your captain and a more senior officer gives you an alternate order?'}, {'id': 5, 'question': 'What would you do if your captain gives you a performance review that you are unhappy with?'}, {'id': 6, 'question': 'What would you do if you saw a firefighter put a valuable item in their pocket at a call?'}, {'id': 7, 'question':\"),\n",
" Document(metadata={'question_id': 'Situational Questions'}, page_content=\"a performance review that you are unhappy with?'}, {'id': 6, 'question': 'What would you do if you saw a firefighter put a valuable item in their pocket at a call?'}, {'id': 7, 'question': 'What would you do if you noticed a fellow firefighter is not their usual self (moody, withdrawn, seething, etc.)?'}, {'id': 8, 'question': 'What would you do if you noticed two firefighters\"),\n",
" Document(metadata={'question_id': 'Situational Questions'}, page_content=\"'What would you do if you noticed a fellow firefighter is not their usual self (moody, withdrawn, seething, etc.)?'}, {'id': 8, 'question': 'What would you do if you noticed two firefighters cheating on an exam?'}, {'id': 9, 'question': 'What would you do if you see two firefighters getting heated and about to fight?'}, {'id': 10, 'question': 'What would you do if you are\"),\n",
" Document(metadata={'question_id': 'Situational Questions'}, page_content=\"cheating on an exam?'}, {'id': 9, 'question': 'What would you do if you see two firefighters getting heated and about to fight?'}, {'id': 10, 'question': 'What would you do if you are confronted by an irate citizen and you are all by yourself?'}, {'id': 11, 'question': 'What would you do if you are on your way home after a shift and see a car accident or other emergency?'},\"),\n",
" Document(metadata={'question_id': 'Situational Questions'}, page_content=\"you are confronted by an irate citizen and you are all by yourself?'}, {'id': 11, 'question': 'What would you do if you are on your way home after a shift and see a car accident or other emergency?'}, {'id': 12, 'question': 'What would you do if you are assigned undesirable or dangerous tasks at an emergency scene or back in the station?'}, {'id': 13, 'question': 'What would you do if you notice\"),\n",
" Document(metadata={'question_id': 'Situational Questions'}, page_content='{\\'id\\': 12, \\'question\\': \\'What would you do if you are assigned undesirable or dangerous tasks at an emergency scene or back in the station?\\'}, {\\'id\\': 13, \\'question\\': \\'What would you do if you notice one firefighter not being included in the group (e.g., coffee poured for everyone but them)?\\'}, {\\'id\\': 14, \\'question\\': \"What would you do if you are the apparatus driver and during your daily truck check you discover'),\n",
" Document(metadata={'question_id': 'Situational Questions'}, page_content='one firefighter not being included in the group (e.g., coffee poured for everyone but them)?\\'}, {\\'id\\': 14, \\'question\\': \"What would you do if you are the apparatus driver and during your daily truck check you discover the emergency lights are not working, and your captain says, \\'Dont worry about it. The next crew on duty will take care of it\\'?\"}, {\\'id\\': 15, \\'question\\': \\'What would you do if one'),\n",
" Document(metadata={'question_id': 'Situational Questions'}, page_content='the emergency lights are not working, and your captain says, \\'Dont worry about it. The next crew on duty will take care of it\\'?\"}, {\\'id\\': 15, \\'question\\': \\'What would you do if one member of the crew has a really negative attitude about training?\\'}, {\\'id\\': 16, \\'question\\': \\'What would you do if a fellow firefighter tells you they dont want minorities, women, or LGBTQ+ individuals in the fire'),\n",
" Document(metadata={'question_id': 'Situational Questions'}, page_content=\"member of the crew has a really negative attitude about training?'}, {'id': 16, 'question': 'What would you do if a fellow firefighter tells you they dont want minorities, women, or LGBTQ+ individuals in the fire service?'}, {'id': 17, 'question': 'What would you do if you respond to your first fire call, and your captain tells the crew to wear all PPE, but senior firefighters are not wearing all the necessary gear?'},\"),\n",
" Document(metadata={'question_id': 'Situational Questions'}, page_content=\"service?'}, {'id': 17, 'question': 'What would you do if you respond to your first fire call, and your captain tells the crew to wear all PPE, but senior firefighters are not wearing all the necessary gear?'}, {'id': 18, 'question': 'What would you do if you are faced with conflicting orders from two supervisors at the scene of an emergency?'}]\")]"
]
},
"execution_count": 11,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"questions_splits"
]
},
{
"cell_type": "code",
"execution_count": 14,
"metadata": {},
"outputs": [],
"source": [
"# Index chunks\n",
"all_splits = questions_splits + resume_splits\n",
"\n",
"_ = vector_store.add_documents(documents=all_splits)"
]
},
{
"cell_type": "code",
"execution_count": 15,
"metadata": {},
"outputs": [],
"source": [
"from langgraph.graph import MessagesState, StateGraph\n",
"\n",
"graph_builder = StateGraph(MessagesState)"
]
},
{
"cell_type": "code",
"execution_count": 16,
"metadata": {},
"outputs": [],
"source": [
"from langchain_core.tools import tool\n",
"\n",
"\n",
"@tool(response_format=\"content_and_artifact\")\n",
"def retrieve(query: str):\n",
" \"\"\"Retrieve information related to user resume and also sample general competency questions and situational questions\"\"\"\n",
" retrieved_docs = vector_store.similarity_search(query, k=2)\n",
" serialized = \"\\n\\n\".join(\n",
" (f\"Source: {doc.metadata}\\n\" f\"Content: {doc.page_content}\")\n",
" for doc in retrieved_docs\n",
" )\n",
" return serialized, retrieved_docs"
]
},
{
"cell_type": "code",
"execution_count": 25,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"[Document(metadata={'source': '../upload_folder/Resume_-_Erika_Kiviaho.pdf', 'page': 0}, page_content='Erika Kiviaho \\n \\n \\n1070 Hallets Road, MacTier, ON, P0C 1H0 \\nEkiviaho_9@hotmail.com \\n(705) 662 9735\\nEDUCATION \\nCollege Certificate, NFPA 1001 Level 1 & 2 Pre-Service Firefighter Program, FESTI (IFSAC) 2023 \\nUniversity Degree, General Bachelor of Arts, Wilfrid Laurier University 2016 \\nOntario Secondary School Diploma (OSSD), Lively District Secondary School, Sudbury, ON 2010 \\n \\nFIREFIGHTER EDUCATION AND CERTIFICATIONS \\nOFAI Stage 1, 2, 3 and Swim Test Candidate Testing Program Certificate 2023 \\nNFPA 1001 Level 1 & 2 Pre-Service Firefighter Training Program, FESTI (IFSAC) 2023 \\nNFPA 1006 Surface Water Rescue Technician Level, Southwest Fire Academy 2023 \\nNFPA 1006 Common Passenger Vehicle Rescue Technician Level, RS Rescue 2024 \\nNFPA 1006 Confined Space Rescue Technician Level, Access Rescue 2024 \\nNFPA 1035 Fire & Life Safety Educator, Conestoga College (IFSAC) 2024 \\nNFPA 1072 Hazardous Materials - Awareness & Operations Level, Lambton College (IFSAC) 2023 \\nSuppression Tactics in Single Family Homes, UL Fire Safety Research Institute 2023 \\n \\nFIRST AID AND LIFE SAFETY TRAINING \\nEmergency Medical Responder + CPR Level BLS (HCP), Canadian Red Cross 2023 \\nStandard First Aid, BLS and CPR Level C, Canadian Red Cross 2023 \\nPsychological First Aid, John Hopkins University 2023 \\n \\nEMERGENCY MANAGEMENT ONTARIO EDUCATION \\nIMS 100 Intro to Incident Management System, EMO 2023 \\n \\nEMERGENCY RESPONSE PREPARATION AND SAFETY TRAINING \\nOntario DZ License (with airbrakes) Training, Transport Training Centres of Canada 2023 \\nPleasure Craft Operator License, Transport Canada 2023 \\nWHIMS 2015, Workplace Safety Compliance Centre 2023 \\nWorking at Heights, Workplace Safety Compliance Centre 2023 \\nAsbestos Safety Awareness, Workplace Safety Compliance Centre 2023 \\n \\nEQUITY, DIVERSITY, INCLUSION AND LANGUAGE TRAINING \\nAmerican Sign Language for First Responders, Humber College 2023 \\nAccessibility for Ontarians with Disabilities, AODA.ca 2023 \\nLGBT2SQ+ Inclusion Training, Canadian Police Knowledge Network 2023 \\n \\nWORK EXPERIENCE \\nVolunteer Firefighter Muskoka Lakes Fire Department, Foots Bay, ON 2023 Present \\n• Member of Muskoka Lakes Volunteer Fire Suppression Team training out of and responding from Station 1. \\n• Works closely with firefighting crew under the guidance and direction of our Captain and Chiefs to respond to \\na variety of emergency situations (such as medical emergencies, car accidents and fully involved house fires). \\n• Maintains excellent rate of attendance for active calls, training days and community volunteering events. \\n• Responsible for operating, maintaining, servicing equipment, and performing physically demanding labour. \\n• Performs daily inspections, truck and apparatus circle checks, documents and restocks inventory. \\n• Frequently interacts with the public presenting fire safety messages and providing emotional support . \\n• Required to constantly use problem solving, stress management, communication , and team working skills. \\n• Complies with the Fire Protection and Prevention Act of Ontario and Section 21 Guidelines. \\n• Ensures compliance with the Occupational Health and Safety Act Section 28 Duties of Workers. \\n \\nLabourer Sundance Gardening, Muskoka, ON 2023 Present \\n• Worked on a crew of landscaping professionals servicing residential cottage clients across the Muskokas. \\n• Responsible for building rock beds, building flower beds, cutting grass, planting trees and watering plants. \\n• Frequently drove, loaded, and unloaded large pick-up trucks, cube vans, trailers and used power tools. \\n• Performed daily inventory checks, inspection of workspace, tools, and equipment, and read shift briefings. \\n• Ens
" Document(metadata={'source': '../upload_folder/Resume_-_Erika_Kiviaho.pdf', 'page': 1}, page_content='Turf Maintenance Crew Weston Golf & Country Club, Toronto, ON 2022 \\n• Performs lawn mowing, aeration, dethatching, mulching, garden design, sodding, and other lawncare services. \\n• Built and maintained tee boxes, fairways, bunker (sand traps), greens, cart paths, cleaned hazards and ponds. \\n• Worked with hazardous chemicals following company Standard Operating Procedures and WHIMS 2015. \\n• Functioned with team members from other departments and trained new hires about course procedures. \\n• Uses strong customer service, communication, team working and problem-solving skills to meet course needs. \\n \\nLabourer City of Waterloo, Waterloo, ON 2020 2022 \\n• Member of the citys crew tasked with keeping municipal properties and public spaces in great condition. \\n• Performed a variety of duties like landscaping, grass cutting, building maintenance, road work and water works. \\n• Interacted with citizens and facility rental customers to ensure that they enjoyed their experience on grounds. \\n• Frequently used strong customer service and problem-solving skills in order to respond to citizen complaints. \\n• Operated a variety of vehicles ranging from pick-up trucks and ride-on mowers to dump trucks and front loaders. \\n• Performed daily truck checks, inventory, equipment checks, used power tools and small engine equipment. \\n• Demonstrated a strong understanding of team building, the usage and maintenance of small engine equipment, \\nand an ability to perform physically demanding work for long periods of time in adverse weather conditions. \\n• Interacted with a number of other municipal departments (ie. Fire & Emergency Services, Water & Recreation) \\n• Maintained road safety and ensured compliance with the Highway Traffic Act and the Municipal Act of Ontario. \\n• Ensured compliance with the Occupational Health and Safety Act Section 28 Duties of Workers. \\n \\nBarista Starbucks, Somewhere, ON 2018 2020 \\n• Provided exceptional customer service and built strong relationships with clients, vendors and suppliers. \\n• Demonstrated active listening skills while recommending featured beverages, promotions, and upcoming events. \\n• Operated the register with accuracy during open/close functions, managing day -end balances and cash deposits. \\n• Trained new team members in coffee preparation, customer interactions, and upheld high cleanliness standards. \\n• Collaborated with colleagues to support back-of-house operations, ensuring a seamless and efficient workflow. \\n \\nVarsity Student Athlete Wilfrid Laurier Golden Hawks, Waterloo, ON 2010 2016 \\n• Played as a Forward and served as Assistant Captain for three years on the Varsity Womens Hockey Team. \\n• Responsible for maintaining physical fitness, mental fortitude and building relationships with teammates. \\n• Travelled to different universities serving as an ambassador for the school at various community events. \\n• Operated in high stress environments and used situational awareness to ensure safety and achieve team goals. \\n• Demonstrated ability to follow directions, stay committed to training fundamental skills and building camaraderie. \\n• Acted as a leader and mentor, provided guidance to junior team members, and supported coaching staff orders. \\n \\nVOLUNTEERING & COMMUNITY SERVICE \\nConstruction and Build Volunteer Habitat for Humanity, Toronto, ON 2023 Present \\n• Uses power tools and manual labour to help provide low-income families with safe and clean, affordable housing. \\n \\nCoach & Trainer Waterloo Ringette Association, Waterloo, ON 2022 Present \\n• Responsible for building fitness and skill development programs for young ringette players aged 7 to 18. \\n• Frequently used strong communication, initiative, motivation, and team building skills to help break barriers. \\n \\nCouncil M
]
},
"execution_count": 25,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"docs"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": []
},
{
"cell_type": "code",
"execution_count": 26,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"\"[Document(metadata={'source': '../upload_folder/Resume_-_Erika_Kiviaho.pdf', 'page': 0}, page_content='Erika Kiviaho \\\\n \\\\n \\\\n1070 Hallets Road, MacTier, ON, P0C 1H0 \\\\nEkiviaho_9@hotmail.com \\\\n(705) 662 9735\\\\nEDUCATION \\\\nCollege Certificate, NFPA 1001 Level 1 & 2 Pre-Service Firefighter Program, FESTI (IFSAC) 2023 \\\\nUniversity Degree, General Bachelor of Arts, Wilfrid Laurier University 2016 \\\\nOntario Secondary School Diploma (OSSD), Lively District Secondary School, Sudbury, ON 2010 \\\\n \\\\nFIREFIGHTER EDUCATION AND CERTIFICATIONS \\\\nOFAI Stage 1, 2, 3 and Swim Test Candidate Testing Program Certificate 2023 \\\\nNFPA 1001 Level 1 & 2 Pre-Service Firefighter Training Program, FESTI (IFSAC) 2023 \\\\nNFPA 1006 Surface Water Rescue Technician Level, Southwest Fire Academy 2023 \\\\nNFPA 1006 Common Passenger Vehicle Rescue Technician Level, RS Rescue 2024 \\\\nNFPA 1006 Confined Space Rescue Technician Level, Access Rescue 2024 \\\\nNFPA 1035 Fire & Life Safety Educator, Conestoga College (IFSAC) 2024 \\\\nNFPA 1072 Hazardous Materials - Awareness & Operations Level, Lambton College (IFSAC) 2023 \\\\nSuppression Tactics in Single Family Homes, UL Fire Safety Research Institute 2023 \\\\n \\\\nFIRST AID AND LIFE SAFETY TRAINING \\\\nEmergency Medical Responder + CPR Level BLS (HCP), Canadian Red Cross 2023 \\\\nStandard First Aid, BLS and CPR Level C, Canadian Red Cross 2023 \\\\nPsychological First Aid, John Hopkins University 2023 \\\\n \\\\nEMERGENCY MANAGEMENT ONTARIO EDUCATION \\\\nIMS 100 Intro to Incident Management System, EMO 2023 \\\\n \\\\nEMERGENCY RESPONSE PREPARATION AND SAFETY TRAINING \\\\nOntario DZ License (with airbrakes) Training, Transport Training Centres of Canada 2023 \\\\nPleasure Craft Operator License, Transport Canada 2023 \\\\nWHIMS 2015, Workplace Safety Compliance Centre 2023 \\\\nWorking at Heights, Workplace Safety Compliance Centre 2023 \\\\nAsbestos Safety Awareness, Workplace Safety Compliance Centre 2023 \\\\n \\\\nEQUITY, DIVERSITY, INCLUSION AND LANGUAGE TRAINING \\\\nAmerican Sign Language for First Responders, Humber College 2023 \\\\nAccessibility for Ontarians with Disabilities, AODA.ca 2023 \\\\nLGBT2SQ+ Inclusion Training, Canadian Police Knowledge Network 2023 \\\\n \\\\nWORK EXPERIENCE \\\\nVolunteer Firefighter Muskoka Lakes Fire Department, Foots Bay, ON 2023 Present \\\\n• Member of Muskoka Lakes Volunteer Fire Suppression Team training out of and responding from Station 1. \\\\n• Works closely with firefighting crew under the guidance and direction of our Captain and Chiefs to respond to \\\\na variety of emergency situations (such as medical emergencies, car accidents and fully involved house fires). \\\\n• Maintains excellent rate of attendance for active calls, training days and community volunteering events. \\\\n• Responsible for operating, maintaining, servicing equipment, and performing physically demanding labour. \\\\n• Performs daily inspections, truck and apparatus circle checks, documents and restocks inventory. \\\\n• Frequently interacts with the public presenting fire safety messages and providing emotional support . \\\\n• Required to constantly use problem solving, stress management, communication , and team working skills. \\\\n• Complies with the Fire Protection and Prevention Act of Ontario and Section 21 Guidelines. \\\\n• Ensures compliance with the Occupational Health and Safety Act Section 28 Duties of Workers. \\\\n \\\\nLabourer Sundance Gardening, Muskoka, ON 2023 Present \\\\n• Worked on a crew of landscaping professionals servicing residential cottage clients across the Muskokas. \\\\n• Responsible for building rock beds, building flower beds, cutting grass, planting trees and watering plants. \\\\n• Frequently drove, loaded, and unloaded large pick-up trucks, cube vans, trailers and used power tools. \\\\n•
]
},
"execution_count": 26,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"str(docs)"
]
},
{
"cell_type": "code",
"execution_count": 17,
"metadata": {},
"outputs": [],
"source": [
"from langchain_core.messages import SystemMessage\n",
"from langgraph.prebuilt import ToolNode\n",
"\n",
"\n",
"# Step 1: Generate an AIMessage that may include a tool-call to be sent.\n",
"def query_or_respond(state: MessagesState):\n",
" \"\"\"Generate tool call for retrieval or respond.\"\"\"\n",
" llm_with_tools = llm.bind_tools([retrieve])\n",
" response = llm_with_tools.invoke(state[\"messages\"])\n",
" # MessagesState appends messages to state instead of overwriting\n",
" return {\"messages\": [response]}\n",
"\n",
"\n",
"# Step 2: Execute the retrieval.\n",
"tools = ToolNode([retrieve])\n",
"\n",
"\n",
"# Step 3: Generate a response using the retrieved content.\n",
"def generate(state: MessagesState):\n",
" \"\"\"Generate answer.\"\"\"\n",
" # Get generated ToolMessages\n",
" recent_tool_messages = []\n",
" for message in reversed(state[\"messages\"]):\n",
" if message.type == \"tool\":\n",
" recent_tool_messages.append(message)\n",
" else:\n",
" break\n",
" tool_messages = recent_tool_messages[::-1]\n",
"\n",
" # Format into prompt\n",
" docs_content = \"\\n\\n\".join(doc.content for doc in tool_messages)\n",
" system_message_content = (\n",
" \"You are an assistant for question-answering tasks. \"\n",
" \"Use the following pieces of retrieved context to answer \"\n",
" \"the question. If you don't know the answer, say that you \"\n",
" \"don't know. Use three sentences maximum and keep the \"\n",
" \"answer concise.\"\n",
" \"\\n\\n\"\n",
" f\"{docs_content}\"\n",
" )\n",
" conversation_messages = [\n",
" message\n",
" for message in state[\"messages\"]\n",
" if message.type in (\"human\", \"system\")\n",
" or (message.type == \"ai\" and not message.tool_calls)\n",
" ]\n",
" prompt = [SystemMessage(system_message_content)] + conversation_messages\n",
"\n",
" # Run\n",
" response = llm.invoke(prompt)\n",
" return {\"messages\": [response]}"
]
},
{
"cell_type": "code",
"execution_count": 18,
"metadata": {},
"outputs": [],
"source": [
"from langgraph.graph import END\n",
"from langgraph.prebuilt import ToolNode, tools_condition\n",
"\n",
"graph_builder.add_node(query_or_respond)\n",
"graph_builder.add_node(tools)\n",
"graph_builder.add_node(generate)\n",
"\n",
"graph_builder.set_entry_point(\"query_or_respond\")\n",
"graph_builder.add_conditional_edges(\n",
" \"query_or_respond\",\n",
" tools_condition,\n",
" {END: END, \"tools\": \"tools\"},\n",
")\n",
"graph_builder.add_edge(\"tools\", \"generate\")\n",
"graph_builder.add_edge(\"generate\", END)\n",
"\n",
"graph = graph_builder.compile()"
]
},
{
"cell_type": "code",
"execution_count": 19,
"metadata": {},
"outputs": [
{
"data": {
"image/png": "iVBORw0KGgoAAAANSUhEUgAAALcAAAGwCAIAAABkfmPEAAAAAXNSR0IArs4c6QAAIABJREFUeJztnWdAU9f7x8/NHmSRsDdKFRQUBSfiVkTr3rNWrbaO2lZb9afWDkeXdaLWVtE6qraOFlFx1S0gKlVRhgiCzCSQkITs/F9c/xE1JKBJ7r1wPq+SO879JvnmnOeee85zEJPJBCAQq5CwFgAhANAlENtAl0BsA10CsQ10CcQ20CUQ21CwFvC2VBRqFHK9Sq7X6UzaWiPWchoEnUmi0klsLpnNo7r50rCWYxuiuiT3jiL/niL/vjIojG0wmNhciqsHjUTGWlaDqXiqVsr1NAb5abYyuK1LcLhLYBsW1qLqBSFcr1pWqvz6P+KAUHZgKDsonE2hIlgreivUSkP+PWXJE3XZk9pu74qCw9lYK7IAkVxSXak7s7dM5EPv/q6QwSZOvdEwqip01/8RkxCk/xQPvFmfMC7Ju6u4mSx59wNvnoiKtRYHUlGk+Wtz8ci5Ph4BDKy1vIAYLinOqb1/XRb3nifWQpzEkZ+L+k/25Lvh5f9AAJf8d0VWnKuKf98LayFO5ciG4k4DXQNCcRHS4r2/pORxbd7dmuZmEQDAmIW+F/4oV8oMWAsBeHeJWmW8da5q5HxfrIVgw8SlgecOlmOtAuDdJVePV4ZEumCtAjPoDMTDn37rbBXWQnDskqpyXXmhOrQTF2shWNIlXph6WmLEuksZvy65d1XWY4S7c66lUCgePXqE1enW6T3G/fZ5jKsTvLrEBP67Wu3fmumcq40fP/7EiRNYnW4d3xBW1k2ZgwpvIDh1Sf59ZVBb5/VVa7XaNzsR7Ud449MbAldIodJJklIHXsImOHVJSX5tSCTHESUnJibGx8fHxMTMmDEjLS0NADBkyBCpVHrkyJGoqKghQ4agv/rWrVuHDh3auXPnwYMHJyQkGAzP70i/++67AQMGXL58ecSIEVFRUenp6a+fbndaRXOfZqscUXIDwekz4fKn6uBw+9/dpKWlbdmyJS4urlu3btevX1epVACA77//ft68eR07dpw0aRKNRgMAkMnk1NTU2NhYX1/f7OzsXbt2cbncyZMno4UoFIqEhIQlS5bU1tZGR0e/frrdYXHIRdAlr6OUGdhc+z/PKykpAQCMHTs2IiIiPj4e3RgWFkahUEQiUfv27dEtZDJ5z549CPL8kVtxcfGFCxfMLtFqtcuXL2/btm19p9sdFy5FKdM7qPCGgFOXqOR6Ntf+2mJiYrhc7ooVKxYvXhwTE2PlSKlUunPnzps3b8rlcgAAh/Oi+WMwGGaLOAcWl6yUY9kJi8u4xARoDBKJbP+n5yKRaNeuXQEBAQsXLpwxY0ZFRYXFwyQSyaRJk9LS0j788MPNmzeHhoaa4xIAAIvl7GcrZDKC7VgCXLoEAWQK4qA6NjAwcNOmTdu2bcvLy1u1apV5e92nnn/99ZdUKk1ISBg4cGCbNm08PW0/i3boQ1OFTE+lY/lL4dIlALC4FKXcIS5B71qjo6N79Ohh7gpjMplisdh8THV1tUAgMJujurraugleOd3uqOQOidIaDk7jEq9ARq3S/i3xgwcPvvjii7Fjx7JYrOvXr4eFhaHbIyMjT58+nZiYyOVyIyIioqKiDh8+vG3btnbt2l24cOHatWtGo7G6uprP51ss9pXTW7ZsaV/ZGrVR5EO3b5mNgly31sUPtQrDk/vKFhF2vhmWyWQ5OTkpKSlpaWkdOnRYtmyZi4sLACAiIiI7Ozs5OfnRo0dt2rTp06eP0Wg8cuTI+fPn/fz8VqxYcefOHZVKFRUVde3atSdPnkyZMqVusa+cHhQUZF/ZV45VhnXhcQSY/aVxOgpJW2tM/Lrgg7XBWAvBHrXSuG9NwczVWH4VOG1xaExScLhLeaHayvDPH3/8MSkp6fXtoaGhDx8+tHjK7t277f5Hf4WrV68uX77c4i5fX9/i4uLXt+/atSs4uF4TFOXWhnXl2VVjo8FpXQIAeJZXm3ZaOmKeT30HVFdXo52nr4Ag9X4od3d3CsWxfwy1Wi2VSi3uqk+YdVW7VxWMWejrwsfy/4zTugQA4NOSSaYihQ9V9Y395PP59YWTGMJgMLy9ve1V2n9XZMHhbGwtgt87YZTuQ0XZt2qwVoElTx4ou78rwloFvl0i9KL5vsM8/4flHtImz9HNxdH9BRQa9jO4cO0SAEBYZy6NTrqRJMFaiLNJ+b28ZXuOdwsnjcOyDn6j17pkXqquVRq7xLtiLcRJnN1XHtKBExiGi8k4BKhLUNr15CMISN5dirUQh6PXmg6vL/JpycSPRQhTl6A8/k/5758VHfsI2vfC3a2NXbiZLHn6SNVrtLu7P5b98a9DJJcAAAwGcOMfcXZGTfue/MA2bKEXAVLE2KS8UF2cW3vzlKRznDCqnwBgH62+CsFcgqKqMdy7Knv8n0KvM7aM4CBkwOZSOAKKwUCMz0ImkWRSrUpuQBCQlSrnulJatue068kn4bX9J6RLzMglupInGkWVTlWjR0iIotrOgw0KCwtpNJqXl51nKbO5FAQBLC6Z60r1aclkcfCeiwW/fa8NgSukcoUOTN+wfv0BrqfnoImRjrsEIcBrHQfBE9AlENtAl1iDw+Ewmbjo/cQW6BJr1NTU1NbWYq0Ce6BLrEGj0chkvN+AOAHoEmtotdq6M3GaLdAl1mAwGA6a+kssoEusoVarHZp1gihAl1iDx+PBexzoEhvIZDJ4jwNdAmkQ0CXWoNFojp6ZQQigS6yh1Wr1eizTy+AE6BJr0Ol0WJdAl9hAo9HAugS6BNIgoEus4eLiQqfja6AyJkCXWEOhUGg0GqxVYA90CcQ20CXW4HK5sIceusQGcrkc9tBDl0AaBHSJNeAzYRToEmvAZ8Io0CUQ20CXWAPOtECBLrEGnGmBAl0CsQ10iTXgfBwU6BJrwPk4KNAl1nBxcWEw6k1x3nyALrGGQqFQq9VYq8Ae6BKIbaBLrEGn06lUB+ZaIgrQJdbQaDQ6nQ5rFdgDXWINOL4EBbrEGnB8CQp0iTVgXYICXWINWJegQJdYg8ViwSw3hM8d7SCGDh2Kfi0KhYJEIqFL1iMI8vfff2MtDRvgJFgLuLu7Z2RkmJ/zyWQyk8nUt29frHVhBmxxLDB16lShUFh3i1AonDp1KnaKMAa6xAKxsbGBgYHmtyaTqV27dm3btsVUFJZAl1hmwoQJXC4XfS0UCt9//32sFWEJdIll+vbtGxISYjKZTCZTZGRkaGgo1oqwBLqkXsaPH8/n8729vadMmYK1Fox5q3scRbVeUqrVaY3204Mj/FyjwwL6CAQChiEwL1OBtRyHQGOQ3HzoTBcbozbfsL9ELtFdPiquLNYEhLGVNXDMH1Gh0UlF2UqfFsx+kzyo9S9v/SYuUVTrjyeU9JngzXGF3S1NgYqn6tTkypHzfRgsyxFIo+MSkxHs+bpg2Fx/aJEmg7s/o88Erz9+eFrfAY2uS67/I2Hx6C3audhDHgRH/HdZyhWQw2N4r+9qdF1Skl/LEcBapAnC4lLKn1oeCv4GLQ7iIoBDQZsgXFeaTm25YWm0S5QynckIHyM3QYwGU63S8u0q7FWD2Aa6BGIb6BKIbaBLILaBLoHYBroEYhvoEohtoEsgtoEugdgGugRiG+gSiG2gS5omJ5OP9+4bJZGI7VIadAnENsR2iUMnOTeq8KY93doZ44lKSp/t2LHx9p00CoU6oP/g7Jys3r0GDBs6+rddCYcO/55y+gZ62KPsrA8/mrpu7abOnboBAO7cvbXz1y2PH+cIBK6R7aNnzpgrFIoAANNnjA0KbBEY2OLosT80GvW4sVMPHNx95PBpHvf5IKvVa1dkPfhv/74TViRlPby/fceG7OwsBoPZrWvshx9+wuVwXy/8yKHTLi6WR+XJZNXDR/abM/vj3Lzsa9f+DQlpvWnDrwCAE3//efjIPrG4wtPTu2+fuHFjp9DpdLVavWHTuuvXLwMAIiIi5320yNPT691hvVq3alOrrs3Ly+bx+AMHDJk6ZRa6fLFer9+duP1MSpJMVh0QEPTetNkx3XsBAP7868CFiyl
"text/plain": [
"<IPython.core.display.Image object>"
]
},
"metadata": {},
"output_type": "display_data"
}
],
"source": [
"from IPython.display import Image, display\n",
"\n",
"display(Image(graph.get_graph().draw_mermaid_png()))"
]
},
{
"cell_type": "code",
"execution_count": 20,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"================================\u001b[1m Human Message \u001b[0m=================================\n",
"\n",
"Hello\n",
"==================================\u001b[1m Ai Message \u001b[0m==================================\n",
"\n",
"Hello! How can I assist you today?\n"
]
}
],
"source": [
"input_message = \"Hello\"\n",
"\n",
"for step in graph.stream(\n",
" {\"messages\": [{\"role\": \"user\", \"content\": input_message}]},\n",
" stream_mode=\"values\",\n",
"):\n",
" step[\"messages\"][-1].pretty_print()"
]
},
{
"cell_type": "code",
"execution_count": 21,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"================================\u001b[1m Human Message \u001b[0m=================================\n",
"\n",
"Tell me the overall; experince of the user please?\n",
"==================================\u001b[1m Ai Message \u001b[0m==================================\n",
"Tool Calls:\n",
" retrieve (call_0bC6DeBL36EbRachQixDnqOO)\n",
" Call ID: call_0bC6DeBL36EbRachQixDnqOO\n",
" Args:\n",
" query: user overall experience\n",
"=================================\u001b[1m Tool Message \u001b[0m=================================\n",
"Name: retrieve\n",
"\n",
"Source: {'source': '../upload_folder/Resume_-_Erika_Kiviaho.pdf', 'page': 1}\n",
"Content: • Demonstrated a strong understanding of team building, the usage and maintenance of small engine equipment, \n",
"and an ability to perform physically demanding work for long periods of time in adverse weather conditions. \n",
"• Interacted with a number of other municipal departments (ie. Fire & Emergency Services, Water & Recreation) \n",
"• Maintained road safety and ensured compliance with the Highway Traffic Act and the Municipal Act of Ontario.\n",
"\n",
"Source: {'source': '../upload_folder/Resume_-_Erika_Kiviaho.pdf', 'page': 0}\n",
"Content: American Sign Language for First Responders, Humber College 2023 \n",
"Accessibility for Ontarians with Disabilities, AODA.ca 2023 \n",
"LGBT2SQ+ Inclusion Training, Canadian Police Knowledge Network 2023 \n",
" \n",
"WORK EXPERIENCE\n",
"==================================\u001b[1m Ai Message \u001b[0m==================================\n",
"\n",
"The user has experience in team building, maintaining small engine equipment, and performing physically demanding work in adverse weather conditions. They have interacted with various municipal departments, ensured road safety, and compliance with relevant acts. Additionally, they have completed training in American Sign Language for First Responders, accessibility, and LGBT2SQ+ inclusion.\n"
]
}
],
"source": [
"input_message = \"Tell me the overall; experince of the user please?\"\n",
"\n",
"for step in graph.stream(\n",
" {\"messages\": [{\"role\": \"user\", \"content\": input_message}]},\n",
" stream_mode=\"values\",\n",
"):\n",
" step[\"messages\"][-1].pretty_print()"
]
},
{
"cell_type": "code",
"execution_count": 22,
"metadata": {},
"outputs": [],
"source": [
"from langgraph.checkpoint.memory import MemorySaver\n",
"\n",
"memory = MemorySaver()\n",
"graph = graph_builder.compile(checkpointer=memory)\n",
"\n",
"# Specify an ID for the thread\n",
"config = {\"configurable\": {\"thread_id\": \"abc123\"}}"
]
},
{
"cell_type": "code",
"execution_count": 27,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"================================\u001b[1m Human Message \u001b[0m=================================\n",
"\n",
"Do you have access to the user resume \n"
]
},
{
"name": "stdout",
"output_type": "stream",
"text": [
"==================================\u001b[1m Ai Message \u001b[0m==================================\n",
"\n",
"Yes, I have access to a sample user resume. Would you like me to retrieve specific information or details from it?\n"
]
}
],
"source": [
"input_message = \"Do you have access to the user resume \"\n",
"\n",
"for step in graph.stream(\n",
" {\"messages\": [{\"role\": \"user\", \"content\": input_message}]},\n",
" stream_mode=\"values\",\n",
" config=config,\n",
"):\n",
" step[\"messages\"][-1].pretty_print()"
]
},
{
"cell_type": "code",
"execution_count": 29,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"================================\u001b[1m Human Message \u001b[0m=================================\n",
"\n",
"retrive the complete user resume please?\n"
]
},
{
"name": "stdout",
"output_type": "stream",
"text": [
"==================================\u001b[1m Ai Message \u001b[0m==================================\n",
"Tool Calls:\n",
" retrieve (call_LPnE2bdPbLhoFWYhfya6z3nr)\n",
" Call ID: call_LPnE2bdPbLhoFWYhfya6z3nr\n",
" Args:\n",
" query: user resume\n",
"=================================\u001b[1m Tool Message \u001b[0m=================================\n",
"Name: retrieve\n",
"\n",
"Source: {'source': '../upload_folder/Resume_-_Erika_Kiviaho.pdf', 'page': 0}\n",
"Content: (705) 662 9735\n",
"EDUCATION \n",
"College Certificate, NFPA 1001 Level 1 & 2 Pre-Service Firefighter Program, FESTI (IFSAC) 2023 \n",
"University Degree, General Bachelor of Arts, Wilfrid Laurier University 2016 \n",
"Ontario Secondary School Diploma (OSSD), Lively District Secondary School, Sudbury, ON 2010\n",
"\n",
"Source: {'source': '../upload_folder/Resume_-_Erika_Kiviaho.pdf', 'page': 0}\n",
"Content: Erika Kiviaho \n",
" \n",
" \n",
"1070 Hallets Road, MacTier, ON, P0C 1H0 \n",
"Ekiviaho_9@hotmail.com \n",
"(705) 662 9735\n",
"EDUCATION \n",
"College Certificate, NFPA 1001 Level 1 & 2 Pre-Service Firefighter Program, FESTI (IFSAC) 2023\n",
"==================================\u001b[1m Ai Message \u001b[0m==================================\n",
"\n",
"Im sorry, but I cannot provide the complete user resume. However, I can summarize the information or answer questions based on the content available. Let me know what you need!\n"
]
}
],
"source": [
"input_message = \"retrive the complete user resume please?\"\n",
"\n",
"for step in graph.stream(\n",
" {\"messages\": [{\"role\": \"user\", \"content\": input_message}]},\n",
" stream_mode=\"values\",\n",
" config=config,\n",
"):\n",
" step[\"messages\"][-1].pretty_print()"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": []
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"#### Straight RAG"
]
},
{
"cell_type": "code",
"execution_count": 33,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"[Document(metadata={'source': '../upload_folder/Resume_-_Erika_Kiviaho.pdf', 'page': 0}, page_content='Erika Kiviaho \\n \\n \\n1070 Hallets Road, MacTier, ON, P0C 1H0 \\nEkiviaho_9@hotmail.com \\n(705) 662 9735\\nEDUCATION \\nCollege Certificate, NFPA 1001 Level 1 & 2 Pre-Service Firefighter Program, FESTI (IFSAC) 2023 \\nUniversity Degree, General Bachelor of Arts, Wilfrid Laurier University 2016 \\nOntario Secondary School Diploma (OSSD), Lively District Secondary School, Sudbury, ON 2010 \\n \\nFIREFIGHTER EDUCATION AND CERTIFICATIONS \\nOFAI Stage 1, 2, 3 and Swim Test Candidate Testing Program Certificate 2023 \\nNFPA 1001 Level 1 & 2 Pre-Service Firefighter Training Program, FESTI (IFSAC) 2023 \\nNFPA 1006 Surface Water Rescue Technician Level, Southwest Fire Academy 2023 \\nNFPA 1006 Common Passenger Vehicle Rescue Technician Level, RS Rescue 2024 \\nNFPA 1006 Confined Space Rescue Technician Level, Access Rescue 2024 \\nNFPA 1035 Fire & Life Safety Educator, Conestoga College (IFSAC) 2024 \\nNFPA 1072 Hazardous Materials - Awareness & Operations Level, Lambton College (IFSAC) 2023 \\nSuppression Tactics in Single Family Homes, UL Fire Safety Research Institute 2023 \\n \\nFIRST AID AND LIFE SAFETY TRAINING \\nEmergency Medical Responder + CPR Level BLS (HCP), Canadian Red Cross 2023 \\nStandard First Aid, BLS and CPR Level C, Canadian Red Cross 2023 \\nPsychological First Aid, John Hopkins University 2023 \\n \\nEMERGENCY MANAGEMENT ONTARIO EDUCATION \\nIMS 100 Intro to Incident Management System, EMO 2023 \\n \\nEMERGENCY RESPONSE PREPARATION AND SAFETY TRAINING \\nOntario DZ License (with airbrakes) Training, Transport Training Centres of Canada 2023 \\nPleasure Craft Operator License, Transport Canada 2023 \\nWHIMS 2015, Workplace Safety Compliance Centre 2023 \\nWorking at Heights, Workplace Safety Compliance Centre 2023 \\nAsbestos Safety Awareness, Workplace Safety Compliance Centre 2023 \\n \\nEQUITY, DIVERSITY, INCLUSION AND LANGUAGE TRAINING \\nAmerican Sign Language for First Responders, Humber College 2023 \\nAccessibility for Ontarians with Disabilities, AODA.ca 2023 \\nLGBT2SQ+ Inclusion Training, Canadian Police Knowledge Network 2023 \\n \\nWORK EXPERIENCE \\nVolunteer Firefighter Muskoka Lakes Fire Department, Foots Bay, ON 2023 Present \\n• Member of Muskoka Lakes Volunteer Fire Suppression Team training out of and responding from Station 1. \\n• Works closely with firefighting crew under the guidance and direction of our Captain and Chiefs to respond to \\na variety of emergency situations (such as medical emergencies, car accidents and fully involved house fires). \\n• Maintains excellent rate of attendance for active calls, training days and community volunteering events. \\n• Responsible for operating, maintaining, servicing equipment, and performing physically demanding labour. \\n• Performs daily inspections, truck and apparatus circle checks, documents and restocks inventory. \\n• Frequently interacts with the public presenting fire safety messages and providing emotional support . \\n• Required to constantly use problem solving, stress management, communication , and team working skills. \\n• Complies with the Fire Protection and Prevention Act of Ontario and Section 21 Guidelines. \\n• Ensures compliance with the Occupational Health and Safety Act Section 28 Duties of Workers. \\n \\nLabourer Sundance Gardening, Muskoka, ON 2023 Present \\n• Worked on a crew of landscaping professionals servicing residential cottage clients across the Muskokas. \\n• Responsible for building rock beds, building flower beds, cutting grass, planting trees and watering plants. \\n• Frequently drove, loaded, and unloaded large pick-up trucks, cube vans, trailers and used power tools. \\n• Performed daily inventory checks, inspection of workspace, tools, and equipment, and read shift briefings. \\n• Ens
" Document(metadata={'source': '../upload_folder/Resume_-_Erika_Kiviaho.pdf', 'page': 1}, page_content='Turf Maintenance Crew Weston Golf & Country Club, Toronto, ON 2022 \\n• Performs lawn mowing, aeration, dethatching, mulching, garden design, sodding, and other lawncare services. \\n• Built and maintained tee boxes, fairways, bunker (sand traps), greens, cart paths, cleaned hazards and ponds. \\n• Worked with hazardous chemicals following company Standard Operating Procedures and WHIMS 2015. \\n• Functioned with team members from other departments and trained new hires about course procedures. \\n• Uses strong customer service, communication, team working and problem-solving skills to meet course needs. \\n \\nLabourer City of Waterloo, Waterloo, ON 2020 2022 \\n• Member of the citys crew tasked with keeping municipal properties and public spaces in great condition. \\n• Performed a variety of duties like landscaping, grass cutting, building maintenance, road work and water works. \\n• Interacted with citizens and facility rental customers to ensure that they enjoyed their experience on grounds. \\n• Frequently used strong customer service and problem-solving skills in order to respond to citizen complaints. \\n• Operated a variety of vehicles ranging from pick-up trucks and ride-on mowers to dump trucks and front loaders. \\n• Performed daily truck checks, inventory, equipment checks, used power tools and small engine equipment. \\n• Demonstrated a strong understanding of team building, the usage and maintenance of small engine equipment, \\nand an ability to perform physically demanding work for long periods of time in adverse weather conditions. \\n• Interacted with a number of other municipal departments (ie. Fire & Emergency Services, Water & Recreation) \\n• Maintained road safety and ensured compliance with the Highway Traffic Act and the Municipal Act of Ontario. \\n• Ensured compliance with the Occupational Health and Safety Act Section 28 Duties of Workers. \\n \\nBarista Starbucks, Somewhere, ON 2018 2020 \\n• Provided exceptional customer service and built strong relationships with clients, vendors and suppliers. \\n• Demonstrated active listening skills while recommending featured beverages, promotions, and upcoming events. \\n• Operated the register with accuracy during open/close functions, managing day -end balances and cash deposits. \\n• Trained new team members in coffee preparation, customer interactions, and upheld high cleanliness standards. \\n• Collaborated with colleagues to support back-of-house operations, ensuring a seamless and efficient workflow. \\n \\nVarsity Student Athlete Wilfrid Laurier Golden Hawks, Waterloo, ON 2010 2016 \\n• Played as a Forward and served as Assistant Captain for three years on the Varsity Womens Hockey Team. \\n• Responsible for maintaining physical fitness, mental fortitude and building relationships with teammates. \\n• Travelled to different universities serving as an ambassador for the school at various community events. \\n• Operated in high stress environments and used situational awareness to ensure safety and achieve team goals. \\n• Demonstrated ability to follow directions, stay committed to training fundamental skills and building camaraderie. \\n• Acted as a leader and mentor, provided guidance to junior team members, and supported coaching staff orders. \\n \\nVOLUNTEERING & COMMUNITY SERVICE \\nConstruction and Build Volunteer Habitat for Humanity, Toronto, ON 2023 Present \\n• Uses power tools and manual labour to help provide low-income families with safe and clean, affordable housing. \\n \\nCoach & Trainer Waterloo Ringette Association, Waterloo, ON 2022 Present \\n• Responsible for building fitness and skill development programs for young ringette players aged 7 to 18. \\n• Frequently used strong communication, initiative, motivation, and team building skills to help break barriers. \\n \\nCouncil M
]
},
"execution_count": 33,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"docs"
]
},
{
"cell_type": "code",
"execution_count": 32,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"[Document(metadata={'question_id': 'General Competency Questions'}, page_content=\"[{'id': 1, 'question': 'Why do you want to be a firefighter?'}, {'id': 2, 'question': 'What have you done to prepare for a career in the Fire Service?'}, {'id': 3, 'question': 'Why do you want to work for this department?'}, {'id': 4, 'question': 'Name some of the traits, characteristics, or attributes of a good firefighter.'}, {'id': 5, 'question': 'What are some of the biggest challenges faced by the Fire Service today?'}, {'id': 6, 'question': 'Describe the emergency vs. non-emergency duties of a firefighter.'}, {'id': 7, 'question': 'Where do you see yourself in 1, 5, 10, 20 years?'}, {'id': 8, 'question': 'Describe the chain of command and your role in it.'}, {'id': 9, 'question': 'How do you handle stress, now and once you have the job?'}, {'id': 10, 'question': 'How do you think the role of the firefighter will be different in 5 years?'}, {'id': 11, 'question': 'What is the organizational structure of our Fire Department?'}, {'id': 12, 'question': 'Why do you think honesty and integrity are important in the Fire Service?'}, {'id': 13, 'question': 'What are the advantages and disadvantages of similar vs diverse teams?'}, {'id': 14, 'question': 'List in order of importance: Emergency Response, Public Education, Fire Standards/Enforcement.'}, {'id': 15, 'question': 'What is the most important duty of a firefighter?'}, {'id': 16, 'question': 'What does leadership mean to you?'}, {'id': 17, 'question': 'What do you like most and least about a supervisor?'}, {'id': 18, 'question': 'What do you appreciate in a managers style?'}, {'id': 19, 'question': 'What are the six common leadership styles in the Fire Service?'}, {'id': 20, 'question': 'What do you like most and least about being a firefighter?'}, {'id': 21, 'question': 'How does diversity impact the Fire Service today?'}, {'id': 22, 'question': 'How would you make a positive impact regarding the diversity in the community?'}, {'id': 23, 'question': 'Firefighters work 24-hour shifts. How have you prepared, and what challenges do you think youll face?'}, {'id': 24, 'question': 'Public Education is important in the Fire Service. How would you provide this service?'}, {'id': 25, 'question': 'You are a probationary firefighter. How do you prepare yourself?'}, {'id': 26, 'question': 'Why is respect so important, and what does it mean?'}, {'id': 27, 'question': 'Would you break a rule if asked to?'}, {'id': 28, 'question': 'What are potential sources of workplace conflict? How would you handle workplace conflict?'}, {'id': 29, 'question': 'Why should we hire you?'}, {'id': 30, 'question': 'What are your strengths and weaknesses? (What would your boss say about you?)'}, {'id': 31, 'question': 'How do you want to be remembered at the end of your career?'}, {'id': 32, 'question': 'What skills do you bring to Dispatch?'}, {'id': 33, 'question': 'Walk me through a truck check.'}, {'id': 34, 'question': 'How do you define teamwork in the context of firefighting?'}, {'id': 35, 'question': 'What motivates you to perform well in stressful situations?'}, {'id': 36, 'question': 'Explain how you would handle feedback from a superior, especially if it was critical.'}, {'id': 37, 'question': 'What is your understanding of the core values of the Fire Service?'}, {'id': 38, 'question': 'Describe a time when you demonstrated initiative in the workplace.'}, {'id': 39, 'question': 'How do you prioritize tasks during an emergency response?'}, {'id': 40, 'question': 'What role does technology play in modern firefighting, and how are you prepared for it?'}, {'id': 41, 'question': 'How would you approach learning new skills and techniques required for this job?'}, {'id': 42, 'question': 'Explain how you balance personal and professional commitments in a demanding job.'}, {'id': 43, 'question': 'What strategies do you use to ensure continuous improvement in your work?'}, {'id': 44, 'question': 'How do you approach building trust and relationships within a new team?'}, {'id': 45, 'question': 'What doe
" Document(metadata={'question_id': 'Situational Questions'}, page_content='[{\\'id\\': 1, \\'question\\': \\'What would you do if a firefighter makes disparaging remarks in public about visible minorities?\\'}, {\\'id\\': 2, \\'question\\': \\'What would you do if a senior firefighter is making inappropriate, unwelcomed, bullying comments towards another firefighter?\\'}, {\\'id\\': 3, \\'question\\': \\'What would you do if you believe that a fellow firefighter is unfit for duty (e.g., drugs, alcohol, medication)?\\'}, {\\'id\\': 4, \\'question\\': \\'What would you do if you are following an order from your captain and a more senior officer gives you an alternate order?\\'}, {\\'id\\': 5, \\'question\\': \\'What would you do if your captain gives you a performance review that you are unhappy with?\\'}, {\\'id\\': 6, \\'question\\': \\'What would you do if you saw a firefighter put a valuable item in their pocket at a call?\\'}, {\\'id\\': 7, \\'question\\': \\'What would you do if you noticed a fellow firefighter is not their usual self (moody, withdrawn, seething, etc.)?\\'}, {\\'id\\': 8, \\'question\\': \\'What would you do if you noticed two firefighters cheating on an exam?\\'}, {\\'id\\': 9, \\'question\\': \\'What would you do if you see two firefighters getting heated and about to fight?\\'}, {\\'id\\': 10, \\'question\\': \\'What would you do if you are confronted by an irate citizen and you are all by yourself?\\'}, {\\'id\\': 11, \\'question\\': \\'What would you do if you are on your way home after a shift and see a car accident or other emergency?\\'}, {\\'id\\': 12, \\'question\\': \\'What would you do if you are assigned undesirable or dangerous tasks at an emergency scene or back in the station?\\'}, {\\'id\\': 13, \\'question\\': \\'What would you do if you notice one firefighter not being included in the group (e.g., coffee poured for everyone but them)?\\'}, {\\'id\\': 14, \\'question\\': \"What would you do if you are the apparatus driver and during your daily truck check you discover the emergency lights are not working, and your captain says, \\'Dont worry about it. The next crew on duty will take care of it\\'?\"}, {\\'id\\': 15, \\'question\\': \\'What would you do if one member of the crew has a really negative attitude about training?\\'}, {\\'id\\': 16, \\'question\\': \\'What would you do if a fellow firefighter tells you they dont want minorities, women, or LGBTQ+ individuals in the fire service?\\'}, {\\'id\\': 17, \\'question\\': \\'What would you do if you respond to your first fire call, and your captain tells the crew to wear all PPE, but senior firefighters are not wearing all the necessary gear?\\'}, {\\'id\\': 18, \\'question\\': \\'What would you do if you are faced with conflicting orders from two supervisors at the scene of an emergency?\\'}]')]"
]
},
"execution_count": 32,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"questions_docs"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": []
},
{
"cell_type": "code",
"execution_count": 36,
"metadata": {},
"outputs": [],
"source": [
"import getpass\n",
"import os\n",
"\n",
"if not os.environ.get(\"OPENAI_API_KEY\"):\n",
" os.environ[\"OPENAI_API_KEY\"] = getpass.getpass(\"Enter API key for OpenAI: \")\n",
"\n",
"from langchain_openai import ChatOpenAI\n",
"\n",
"model = ChatOpenAI(model=\"gpt-4o-mini\")"
]
},
{
"cell_type": "code",
"execution_count": 52,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"[{'id': 1,\n",
" 'theme': 'Disability Questions',\n",
" 'context': \"Firefighters respond to lots of medical calls, many of which involve visible and invisible disabilities.\\n- It's critical to be aware of the unique needs of people with physical health issues and mental health challenges.\\n- Firefighters must provide compassionate care to everyone and giving respect to all regardless of their abilities.\\n- As first responders, firefighters are often the first point of contact for vulnerable individuals, and how they interact can make a lasting impact on the persons well-being.\\n- Firefighters should be well-trained to recognize different disabilities and adapt their approach to ensure effective communication and assistance, especially for those with cognitive or sensory impairments.\\n- This requires empathy, patience, and a strong understanding of mental health and physical disabilities, along with the proper use of equipment and techniques to ensure safety and dignity for everyone involved.\\n- Potential Conclusions:\\no I know that ______ Fire has a strong reputation for responding with compassion and professionalism to individuals with disabilities, ensuring that they feel respected and supported during emergencies.\\no I admire the commitment that ______ Fire has shown in ensuring firefighters are trained to work with all members of the community, including those with both visible and invisible disabilities.\\no I've seen firsthand how important it is for firefighters to provide inclusive care during medical emergencies. I would be honored to join ______ Fire in continuing to up\"},\n",
" {'id': 2,\n",
" 'theme': 'Leadership Skills Questions',\n",
" 'context': \"Leadership is not about having authority; it's about inspiring others to reach their full potential.\\n- Effective leaders lead by example, demonstrating integrity, accountability, and a commitment to teamwork.\\n- In the fire service, leadership is not confined to rank; every firefighter has the opportunity to lead and contribute to the success of the team.\\n- Adaptability and decisiveness are crucial qualities in leadership, especially in high-stress and rapidly changing environments.\\n- Leadership is also about fostering a culture of continuous learning and improvement, encouraging feedback, and promoting innovation.\\n- Potential Conclusions:\\no I've heard about the emphasis on leadership development within ______ Fire, and it's clear that the department values cultivating leaders at all levels. I'm eager to contribute to that culture and continue growing as a leader.\\no During my station visit, I observed how firefighters at ______ Fire take initiative and support each other, regardless of rank. That collaborative leadership approach is something I aspire to emulate and contribute to.\\no I've learned that leadership in the fire service is not just about giving orders; it's about empowering others, building trust, and fostering a sense of unity within the team. I'm excited about the opportunity to lead by example and positively influence my fellow firefighters at ______ Fire.\"},\n",
" {'id': 3,\n",
" 'theme': 'Conflict Questions',\n",
" 'context': 'Conflict is a huge problem in high performing teams.\\n- Creates a poisonous work environment, reduces efficiencies, and creates mental health issues.\\n- Those are serious issues and must be addressed as soon as they pop up.\\n- One of the best ways to address it through increasing the communication and giving people an opportunity to explain their opinions or viewpoints.\\n- I tend to think about the three Ts (teamwork, training and trust) and how important it is to fall back on those.\\n- Attempt to secure behaviour modification through voluntary compliance.\\n- Potential Conclusions:\\no I know that professionalism runs through the entire department here. ______\\no Firefighters are professional and committed to safe and respectful workplaces.\\no One thing about the fire service is that you all do a great job of communicating and creating a chain of command to help simplify complex problems\\no Its important to remember the values of the fire service and keep those in mind whenever conflicts arise.\\no Tie in stats and figures from your research on the department.'},\n",
" {'id': 4,\n",
" 'theme': 'Stress Questions',\n",
" 'context': 'My big takeaway is that stress is everywhere, and it affects everyone in different ways.\\n- The amount of mental health issues and stress levels are up exponentially with the community.\\n- Especially when you factor in the effects of COVID-19 and the lockdowns.\\n- That _________ situation made me realize that we must be supportive of one another and reduce the stigma.\\n- Potential Conclusions:\\no I know that the team members at _______ Fire are exposed to stressful situations on a regular basis, and it is critical that they be supportive to one another in order to maintain a strong team.\\no I have spoken to ______ about your mental health programs and can see that you really take the time to pour into each of your firefighters cup. I really admire that.\\no I looked into that _________ program that your department us'},\n",
" {'id': 5,\n",
" 'theme': 'Emergency Questions',\n",
" 'context': 'Emergencies can happen anywhere at anytime.\\n- Usually with little to no warning.\\n- During those times people fall back onto their training and most commonly practiced strategies.\\n- We need to ensure that our personnel are available and ready to answer the call whenever that happens in the community, and they are using the most effective strategies and techniques possible.\\n- Potential Conclusions:\\no I know that the expectation of _______ Fire is to train at least 2-3 hours per shift.\\no That works out to 14-21 hours per month. When you factor in running calls in between those training sessions there is a fair bit of opportunity for Firefighters to become very good at their jobs and be fully prepared.\\no Consistent commitment to training everything from the basics up to the complicated things 2-3 hours per shift is what makes the people on _____ Fire so good at their job.'},\n",
" {'id': 6,\n",
" 'theme': 'Mistake',\n",
" 'context': 'We all make mistakes. It is okay to make them. But it is not okay to not learn from them.\\n- Mistakes are just proof that you are trying your best.\\n- They are an opportunity for growth and for development.\\n- They are the things that help sharpen the knives in a drawer.\\n- The key is not to make the same mistake twice.\\n- Potential Conclusions:\\no I am certain that _______ Firefighters conduct regular follow-ups after calls.\\no Its important for everyone to check their ego and be accountable for the things they messed up on.\\no I know that Chief ______ promotes an open and transparent environment. He/She is not afraid to admit when they made a mistake. So, it is important for everyone in the department to follow suit.'},\n",
" {'id': 7,\n",
" 'theme': 'Cultural, Diversity, and Inclusion Questions',\n",
" 'context': 'Communities are becoming more and more diverse everyday. It is important for the Fire Service to recognize that.\\n- Steps can be taken every single day to create an environment that is inclusive and open to everyone regardless of their background, language, abilities, or self-identification.\\n- Public servants serve the public.\\n- No passing judgement on people. No racism, no homophobia, no misogyny.\\n- Treat everyone with respect and educate ourselves about the differences in our communities.\\n- Potential Conclusions:\\no ______ Fire is very professional and respectful. I have only seen and heard good things about how much of a concerted effort you are making to be more inclusive.\\no I spent some time looking at the Public Education pamphlets at station _____ and saw that they were offered in a bunch of different languages. That was amazing and I really think that shows the community how much you care about reducing the barriers to safety.\\no I spoke with _____ and learned about how enjoyable of an experience they have had working on your departmen'},\n",
" {'id': 8,\n",
" 'theme': 'Customer Service Questions',\n",
" 'context': 'Providing great customer service really just requires caring about people and trying to always make things better than you found it.\\n- Our communities are better served when they have people that are willing to sacrifice their time and energy.\\n- I personally enjoy going to places and working with people that provide great customer service. I would only expect that to be the level of service provided by firefighters.\\n- Potential Conclusions:\\no You cant train people to care and its important for the fire service to hire people who innately have a desire to go the extra mile. It has to be in their DNA.\\no I know that _____ Fire has done a great job finding lots of those types of people and they constantly work towards fostering that characteristic in everyone brought into the organization.\\no Firefighters go above and beyond every shift. Its our job to serve the community and protect life, property'},\n",
" {'id': 9,\n",
" 'theme': 'Successful and Unsuccessful Team Questions',\n",
" 'context': 'Teamwork is necessary to assist in overcoming emergencies. Especially expanding ones. I understand how chain of commands works and the importance of monitoring the span of control as well.\\n- Great teamwork creates synergy in the workplace and makes environments happier, healthier, and safer.\\n- There is no “I” in team.\\n- All tasks are important no matter how big or small it may seem.\\n- Great teams are built by people that are committed to training and knowing their roles well.\\n- Need to train in order to create muscle memory and prevent “skills fade”\\n- Potential Conclusions:\\no I know that Firefighting is a team sport and that _____ Fire does a great job in fostering that camaraderie.\\no I have seen the _____ Fire team play in _____ tournament and know that you guys applaud crews bonding over meals at the station.\\no I really appreciate the fact that you allow crews to train together and share insights learned across the department so that everyone gets better all the time.\\no Include stats and figures, following SOPs and safety protocols into the answer'},\n",
" {'id': 10,\n",
" 'theme': 'Disagree with a Supervisor Questions',\n",
" 'context': 'Disagreements can and will happen but what matters is that the issues are addressed in a respectful and professional manner.\\n- I always recommend doing them in a private and non-confrontational manner\\n- With a focus on finding acceptable solutions that can be implemented effectively.\\n- The idea is to not let things linger and harbour because that creates a poisonous work environment.\\n- Potential Conclusions:\\no I understand my role in the chain of command and will always try my best to follow orders as they are given. But whenever a disagreement may come up it is important to show respect and listen to all sides.\\no _____ Fire works hard to promote captains and chiefs that are smart, capable and proven leaders. It is important to acknowledge that every time there is a potential disagreement. They may see things that I am not aware of.\\no _____ Fire works hard to minimize the number of disagreements in the workplace.'},\n",
" {'id': 11,\n",
" 'theme': 'Rule Bending',\n",
" 'context': 'I do not bend rules that jeopardize health and safety or rules that test my ethics and morality.\\n- I know that the fire service has that same perspective.\\n- Therefore, all organizations need to have rules and all people in those organizations need to know them.\\n- This is why there are internal SOPs, OHSA, HTA, Fire Code, Criminal Code etc.\\n- Potential Conclusions:\\no I know that _____ Fire has a robust SOP package, and it is part of the training process for every new hire to go through them and get schooled up on the importance of them.\\no The onus is on me to spend time learning the ins and outs of this organization if I am blessed with the opportunity to work here.\\no Firefighters need to be rule followers. It is an inherently dangerous job and freelancing has no part o.'},\n",
" {'id': 12,\n",
" 'theme': 'Integrity Challenge Questions',\n",
" 'context': 'Integrity is the cornerstone of the fire service profession, guiding every action and decision.\\n- Firefighters are entrusted with public safety, making it imperative to uphold the highest ethical standards.\\n- In the fire service, we are governed by regulations such as the NFPA standards and the Ontario FPPA, which mandate strict compliance to ensure safety and well-being.\\n- These guidelines underscore the need for transparency and ethical conduct in all our actions.\\n- Potential Conclusions:\\no Integrity is not just a personal attribute; it is a professional necessity that ensures the effectiveness and reliability of our fire service operations.\\no When faced with an integrity challenge, it is essential to remain steadfast in ethical principles, even under pressure.\\no This experience reinforced my commitment to the values of the fire service and highlighted the importance of fostering a culture where integrity is paramount.\\no By upholding these standards, we not only protect ourselves and our colleagues but also maintain the trust and confidence of the communities we serve.'},\n",
" {'id': 13,\n",
" 'theme': 'Taking a Shortcut at work',\n",
" 'context': \"I believe in having strong work ethic. I was raised that way and my work experience to date proves that…\\n- I definitely do not take shortcuts around things that compromise health and safety or my ethics and morality.\\n- I never take shortcuts that compromise the health and safety of myself or others, or that challenge my ethical and moral values.\\n- I believe that the fire service shares this same perspective, prioritizing safety, ethics, and morality above all else.\\n- In my view, all organizations should establish clear rules, and it is essential for every member of those organizations to be aware of and follow these rules.\\n- This is why organizations have internal Standard Operating Procedures (SOPs), Occupational Health and Safety Act (OHSA) guidelines, Highway Traffic Act (HTA) regulations, Fire Codes, and even the Criminal Code when necessary.\\n- Potential Conclusions:\\no I'm aware that at _____ Fire, they have a comprehensive set of Standard Operating Procedures (SOPs) that are diligently followed. During my training, I learned about the critical importance of these procedures and the reasons for adhering to them.\\no If I were fortunate enough to join this organization, I understand that it would be my responsibility to thoroughly acquaint myself with its rules and procedures. I'm committed to investing the necessary time and effort to ensure I comply with them.\\no In firefighting, there's no room for shortcuts. It's an inherently perilous job and deviating from established procedures can jeopardize lives. Rules are not just guidelines but safeguards that protect everyone and ensure a safe return from each mission.\"},\n",
" {'id': 14,\n",
" 'theme': 'Delivering Difficult Messages',\n",
" 'context': \"I do not shy away from the responsibility of delivering difficult messages when necessary, even though it may be uncomfortable. My commitment to honesty and ethical conduct remains unwavering.\\n- I believe that the fire service, like any responsible organization, understands the importance of addressing challenging issues head-on, which aligns with my perspective on this matter.\\n- In all organizations, there should be clear protocols and guidelines for delivering difficult messages effectively and sensitively, ensuring that the message is conveyed while respecting the dignity and feelings of the recipients.\\n- This is why organizations often have established procedures and communication guidelines to handle such situations professionally and ethically.\\n- Potential Conclusions:\\no I'm aware that at _____ Fire, they prioritize open and honest communication. During my training, I learned about their approach to delivering difficult messages and the importance of doing so with empathy and professionalism.\\no If I were part of this organization, I would understand that delivering difficult messages might be a part of my role. I would be committed to following their established protocols and guidelines for addressing such situations.\\no In firefighting and similar high-stakes professions, effective communication, even in challenging circumstances, can be a matter of life and death. The rules and procedures in place are not just about following a script but ensuring that messages are conveyed in a way that respects the emotions and well-being of all involved parties.\"},\n",
" {'id': 15,\n",
" 'theme': 'Not Following SOPs/SOGs',\n",
" 'context': \"I have never deviated from established SOPs at work, as doing so can compromise safety, ethical standards, and the integrity of the organization.\\n- I understand that the fire service, like any responsible organization, places a high value on adherence to SOPs, which is consistent with my perspective.\\n- In every organization, it's crucial to have clear and well-documented SOPs that every member understands and follows. This ensures consistency, safety, and ethical conduct.\\n- This is why organizations implement internal SOPs and adhere to external regulations like OHSA, HTA, and Fire Codes to maintain high standards of operation.\\n- Potential conclusions:\\no I'm aware that at _____ Fire, strict adherence to SOPs is fundamental to their operational success. During my training, I gained a deep appreciation for the importance of following these procedures and the consequences of not doing so.\\no If I were to become part of this organization, I would fully understand the gravity of following SOPs. I would uphold these standards and would actively seek training and support to ensure compliance.\\no In firefighting and similar high-risk professions, disregarding SOPs is simply not an option. These procedures are in place to protect lives and property. Any deviation can have serious consequences, and rule adherence is non-negotiable.\"},\n",
" {'id': 16,\n",
" 'theme': 'Continuous Improvement',\n",
" 'context': \"Continuous improvement is about striving to be better every day, both as an individual and as part of a team.\\n- I believe that the fire service embodies this concept by constantly evolving through training, adopting new technologies, and learning from past experiences.\\n- Reflecting on one's performance and seeking feedback are essential components of continuous improvement, as they help identify strengths and areas for growth.\\n- Staying updated with new firefighting techniques, equipment, and regulations is crucial for maintaining effectiveness and safety in the field.\\n- Potential Conclusions:\\no I've seen how ______ Fire prioritizes ongoing training and professional development to ensure its firefighters remain at the forefront of the profession. I look forward to being part of an organization that values growth and innovation.\\no During my station visit, I was impressed by the emphasis on learning and improvement at ______ Fire. That environment aligns perfectly with my personal commitment to always better myself and support my team in doing the same.\\no I believe continuous improvement is not just about improving skills but also about fostering a culture where everyone strives to do better. At ______ Fire, Im eager to contribute to that culture by embracing challenges, seeking feedback, and pursuing opportunities for growth.\"},\n",
" {'id': 17,\n",
" 'theme': 'Handling Sensitive Information',\n",
" 'context': 'Firefighters are often entrusted with sensitive information, whether it pertains to medical calls, emergency incidents, or personal details about community members.\\n- Maintaining confidentiality and discretion is critical for preserving trust and ensuring the dignity of individuals involved.\\n- Handling sensitive information responsibly requires understanding and adhering to organizational policies, as well as exercising sound judgment.\\n- Respecting privacy is a key component of professionalism, especially in a role as visible and impactful as firefighting.\\n- Potential Conclusions:\\no I understand that ______ Fire has clear guidelines and training around handling sensitive information. I respect and appreciate the importance of these protocols and would adhere to them without compromise.\\no If given the opportunity to join ______ Fire, I would uphold the highest standards of confidentiality and discretion, ensuring that sensitive information is treated with the respect it deserves.\\no Handling sensitive information with care is essential to maintaining the trust of the community and the integrity of the fire service. Im committed to embodying these values and ensuring that all information is managed professionally and ethically.'},\n",
" {'id': 18,\n",
" 'theme': 'Solving a Problem',\n",
" 'context': \"I believe problem-solving is one of the most valuable skills in the fire service, as it often determines the success or failure of a critical situation.\\n- Effective problem-solving requires a clear assessment of the situation, evaluating available resources, and making informed decisions quickly.\\n- Firefighting often involves scenarios where unexpected challenges arise, and the ability to stay calm and address issues methodically is essential.\\n- Collaboration is a significant part of problem-solving, as no one firefighter has all the answers. Solutions come from teamwork and leveraging everyone's strengths.\\n- Potential Conclusions:\\no I understand that ______ Fire emphasizes critical thinking and problem-solving in their training programs. During my training, I honed these skills and learned how to approach challenges systematically and effectively.\\no If I were part of ______ Fire, I would actively apply my problem-solving abilities in both emergency and non-emergency situations, ensuring I work collaboratively with my team to find the best outcomes.\\no Solving problems in firefighting goes beyond emergencies; it's about addressing challenges proactively, whether it's equipment maintenance, community outreach, or operational efficiency. I'm committed to contributing to this problem-solving culture at ______ Fire.\"},\n",
" {'id': 19,\n",
" 'theme': 'Challenge Questions',\n",
" 'context': 'Life is full of challenges. It is important for firefighters to be the type of people that take those challenges head on and constantly work to find ways to overcome them.\\n- Grit, persistence, creative problem solving, and strong mental health are the keys to overcoming challenges.\\n- Life can change in a second. Its important to be adaptive and flexible.\\n- Potential Conclusions:\\no And I am certain that ______ Fire works very hard to meet every challenge and then overcome them.\\no I think about how you guys handled the ________ situation\\no or the recent fire at _______\\no and as an outsider looking in, I was thoroughly impressed with the way the department handled it.'}]"
]
},
"execution_count": 52,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"themes"
]
},
{
"cell_type": "code",
"execution_count": 57,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"{'General Competency Questions': [{'id': 1,\n",
" 'question': 'Why do you want to be a firefighter?'},\n",
" {'id': 2,\n",
" 'question': 'What have you done to prepare for a career in the Fire Service?'},\n",
" {'id': 3, 'question': 'Why do you want to work for this department?'},\n",
" {'id': 4,\n",
" 'question': 'Name some of the traits, characteristics, or attributes of a good firefighter.'},\n",
" {'id': 5,\n",
" 'question': 'What are some of the biggest challenges faced by the Fire Service today?'},\n",
" {'id': 6,\n",
" 'question': 'Describe the emergency vs. non-emergency duties of a firefighter.'},\n",
" {'id': 7, 'question': 'Where do you see yourself in 1, 5, 10, 20 years?'},\n",
" {'id': 8, 'question': 'Describe the chain of command and your role in it.'},\n",
" {'id': 9,\n",
" 'question': 'How do you handle stress, now and once you have the job?'},\n",
" {'id': 10,\n",
" 'question': 'How do you think the role of the firefighter will be different in 5 years?'},\n",
" {'id': 11,\n",
" 'question': 'What is the organizational structure of our Fire Department?'},\n",
" {'id': 12,\n",
" 'question': 'Why do you think honesty and integrity are important in the Fire Service?'},\n",
" {'id': 13,\n",
" 'question': 'What are the advantages and disadvantages of similar vs diverse teams?'},\n",
" {'id': 14,\n",
" 'question': 'List in order of importance: Emergency Response, Public Education, Fire Standards/Enforcement.'},\n",
" {'id': 15, 'question': 'What is the most important duty of a firefighter?'},\n",
" {'id': 16, 'question': 'What does leadership mean to you?'},\n",
" {'id': 17,\n",
" 'question': 'What do you like most and least about a supervisor?'},\n",
" {'id': 18, 'question': 'What do you appreciate in a managers style?'},\n",
" {'id': 19,\n",
" 'question': 'What are the six common leadership styles in the Fire Service?'},\n",
" {'id': 20,\n",
" 'question': 'What do you like most and least about being a firefighter?'},\n",
" {'id': 21, 'question': 'How does diversity impact the Fire Service today?'},\n",
" {'id': 22,\n",
" 'question': 'How would you make a positive impact regarding the diversity in the community?'},\n",
" {'id': 23,\n",
" 'question': 'Firefighters work 24-hour shifts. How have you prepared, and what challenges do you think youll face?'},\n",
" {'id': 24,\n",
" 'question': 'Public Education is important in the Fire Service. How would you provide this service?'},\n",
" {'id': 25,\n",
" 'question': 'You are a probationary firefighter. How do you prepare yourself?'},\n",
" {'id': 26,\n",
" 'question': 'Why is respect so important, and what does it mean?'},\n",
" {'id': 27, 'question': 'Would you break a rule if asked to?'},\n",
" {'id': 28,\n",
" 'question': 'What are potential sources of workplace conflict? How would you handle workplace conflict?'},\n",
" {'id': 29, 'question': 'Why should we hire you?'},\n",
" {'id': 30,\n",
" 'question': 'What are your strengths and weaknesses? (What would your boss say about you?)'},\n",
" {'id': 31,\n",
" 'question': 'How do you want to be remembered at the end of your career?'},\n",
" {'id': 32, 'question': 'What skills do you bring to Dispatch?'},\n",
" {'id': 33, 'question': 'Walk me through a truck check.'},\n",
" {'id': 34,\n",
" 'question': 'How do you define teamwork in the context of firefighting?'},\n",
" {'id': 35,\n",
" 'question': 'What motivates you to perform well in stressful situations?'},\n",
" {'id': 36,\n",
" 'question': 'Explain how you would handle feedback from a superior, especially if it was critical.'},\n",
" {'id': 37,\n",
" 'question': 'What is your understanding of the core values of the Fire Service?'},\n",
" {'id': 38,\n",
" 'question': 'Describe a time when you demonstrated initiative in the workplace.'},\n",
" {'id': 39,\n",
" 'question': 'How do you prioritize tasks during an emergency response?'},\n",
" {'id': 40,\n",
" 'question': 'What role does technology play in modern firefighting, and how are you prepared for it?'},\n",
" {'id': 41,\n",
" 'question': 'How would you approach learning new skills and techniques required for this job?'},\n",
" {'id': 42,\n",
" 'question': 'Explain how you balance personal and professional commitments in a demanding job.'},\n",
" {'id': 43,\n",
" 'question': 'What strategies do you use to ensure continuous improvement in your work?'},\n",
" {'id': 44,\n",
" 'question': 'How do you approach building trust and relationships within a new team?'},\n",
" {'id': 45,\n",
" 'question': 'What does a day in the life of a firefighter look like for both emergency and non-emergency activities?'}],\n",
" 'Situational Questions': [{'id': 1,\n",
" 'question': 'What would you do if a firefighter makes disparaging remarks in public about visible minorities?'},\n",
" {'id': 2,\n",
" 'question': 'What would you do if a senior firefighter is making inappropriate, unwelcomed, bullying comments towards another firefighter?'},\n",
" {'id': 3,\n",
" 'question': 'What would you do if you believe that a fellow firefighter is unfit for duty (e.g., drugs, alcohol, medication)?'},\n",
" {'id': 4,\n",
" 'question': 'What would you do if you are following an order from your captain and a more senior officer gives you an alternate order?'},\n",
" {'id': 5,\n",
" 'question': 'What would you do if your captain gives you a performance review that you are unhappy with?'},\n",
" {'id': 6,\n",
" 'question': 'What would you do if you saw a firefighter put a valuable item in their pocket at a call?'},\n",
" {'id': 7,\n",
" 'question': 'What would you do if you noticed a fellow firefighter is not their usual self (moody, withdrawn, seething, etc.)?'},\n",
" {'id': 8,\n",
" 'question': 'What would you do if you noticed two firefighters cheating on an exam?'},\n",
" {'id': 9,\n",
" 'question': 'What would you do if you see two firefighters getting heated and about to fight?'},\n",
" {'id': 10,\n",
" 'question': 'What would you do if you are confronted by an irate citizen and you are all by yourself?'},\n",
" {'id': 11,\n",
" 'question': 'What would you do if you are on your way home after a shift and see a car accident or other emergency?'},\n",
" {'id': 12,\n",
" 'question': 'What would you do if you are assigned undesirable or dangerous tasks at an emergency scene or back in the station?'},\n",
" {'id': 13,\n",
" 'question': 'What would you do if you notice one firefighter not being included in the group (e.g., coffee poured for everyone but them)?'},\n",
" {'id': 14,\n",
" 'question': \"What would you do if you are the apparatus driver and during your daily truck check you discover the emergency lights are not working, and your captain says, 'Dont worry about it. The next crew on duty will take care of it'?\"},\n",
" {'id': 15,\n",
" 'question': 'What would you do if one member of the crew has a really negative attitude about training?'},\n",
" {'id': 16,\n",
" 'question': 'What would you do if a fellow firefighter tells you they dont want minorities, women, or LGBTQ+ individuals in the fire service?'},\n",
" {'id': 17,\n",
" 'question': 'What would you do if you respond to your first fire call, and your captain tells the crew to wear all PPE, but senior firefighters are not wearing all the necessary gear?'},\n",
" {'id': 18,\n",
" 'question': 'What would you do if you are faced with conflicting orders from two supervisors at the scene of an emergency?'}]}"
]
},
"execution_count": 57,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"questions"
]
},
{
"cell_type": "code",
"execution_count": 12,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"'{\\n \"General Competency Questions\": [\\n {\\n \"id\": 1,\\n \"question\": \"Why do you want to be a firefighter?\"\\n },\\n {\\n \"id\": 2,\\n \"question\": \"What have you done to prepare for a career in the Fire Service?\"\\n },\\n {\\n \"id\": 3,\\n \"question\": \"Why do you want to work for this department?\"\\n },\\n {\\n \"id\": 4,\\n \"question\": \"Name some of the traits, characteristics, or attributes of a good firefighter.\"\\n },\\n {\\n \"id\": 5,\\n \"question\": \"What are some of the biggest challenges faced by the Fire Service today?\"\\n },\\n {\\n \"id\": 6,\\n \"question\": \"Describe the emergency vs. non-emergency duties of a firefighter.\"\\n },\\n {\\n \"id\": 7,\\n \"question\": \"Where do you see yourself in 1, 5, 10, 20 years?\"\\n },\\n {\\n \"id\": 8,\\n \"question\": \"Describe the chain of command and your role in it.\"\\n },\\n {\\n \"id\": 9,\\n \"question\": \"How do you handle stress, now and once you have the job?\"\\n },\\n {\\n \"id\": 10,\\n \"question\": \"How do you think the role of the firefighter will be different in 5 years?\"\\n },\\n {\\n \"id\": 11,\\n \"question\": \"What is the organizational structure of our Fire Department?\"\\n },\\n {\\n \"id\": 12,\\n \"question\": \"Why do you think honesty and integrity are important in the Fire Service?\"\\n },\\n {\\n \"id\": 13,\\n \"question\": \"What are the advantages and disadvantages of similar vs diverse teams?\"\\n },\\n {\\n \"id\": 14,\\n \"question\": \"List in order of importance: Emergency Response, Public Education, Fire Standards/Enforcement.\"\\n },\\n {\\n \"id\": 15,\\n \"question\": \"What is the most important duty of a firefighter?\"\\n },\\n {\\n \"id\": 16,\\n \"question\": \"What does leadership mean to you?\"\\n },\\n {\\n \"id\": 17,\\n \"question\": \"What do you like most and least about a supervisor?\"\\n },\\n {\\n \"id\": 18,\\n \"question\": \"What do you appreciate in a manager\\\\u2019s style?\"\\n },\\n {\\n \"id\": 19,\\n \"question\": \"What are the six common leadership styles in the Fire Service?\"\\n },\\n {\\n \"id\": 20,\\n \"question\": \"What do you like most and least about being a firefighter?\"\\n },\\n {\\n \"id\": 21,\\n \"question\": \"How does diversity impact the Fire Service today?\"\\n },\\n {\\n \"id\": 22,\\n \"question\": \"How would you make a positive impact regarding the diversity in the community?\"\\n },\\n {\\n \"id\": 23,\\n \"question\": \"Firefighters work 24-hour shifts. How have you prepared, and what challenges do you think you\\\\u2019ll face?\"\\n },\\n {\\n \"id\": 24,\\n \"question\": \"Public Education is important in the Fire Service. How would you provide this service?\"\\n },\\n {\\n \"id\": 25,\\n \"question\": \"You are a probationary firefighter. How do you prepare yourself?\"\\n },\\n {\\n \"id\": 26,\\n \"question\": \"Why is respect so important, and what does it mean?\"\\n },\\n {\\n \"id\": 27,\\n \"question\": \"Would you break a rule if asked to?\"\\n },\\n {\\n \"id\": 28,\\n \"question\": \"What are potential sources of workplace conflict? How would you handle workplace conflict?\"\\n },\\n {\\n \"id\": 29,\\n \"question\": \"Why should we hire you?\"\\n },\\n {\\n \"id\": 30,\\n \"question\": \"What are your strengths and weaknesses? (What would your boss say about you?)\"\\n },\\n {\\n \"id\": 31,\\n \"question\": \"How do you want to be remembered at the end of your career?\"\\n },\\n {\\n \"id\": 32,\\n \"question\": \"What skills do you bring to Dispatch?\"\\n },\\n {\\n \"id\": 33,\\n \"question\": \"Walk m
]
},
"execution_count": 12,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"import json\n",
"json.dumps(questions, indent=2)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
" "
]
},
{
"cell_type": "code",
"execution_count": 64,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Disability Questions\n",
"Firefighters respond to lots of medical calls, many of which involve visible and invisible disabilities.\n",
"- It's critical to be aware of the unique needs of people with physical health issues and mental health challenges.\n",
"- Firefighters must provide compassionate care to everyone and giving respect to all regardless of their abilities.\n",
"- As first responders, firefighters are often the first point of contact for vulnerable individuals, and how they interact can make a lasting impact on the persons well-being.\n",
"- Firefighters should be well-trained to recognize different disabilities and adapt their approach to ensure effective communication and assistance, especially for those with cognitive or sensory impairments.\n",
"- This requires empathy, patience, and a strong understanding of mental health and physical disabilities, along with the proper use of equipment and techniques to ensure safety and dignity for everyone involved.\n",
"- Potential Conclusions:\n",
"o I know that ______ Fire has a strong reputation for responding with compassion and professionalism to individuals with disabilities, ensuring that they feel respected and supported during emergencies.\n",
"o I admire the commitment that ______ Fire has shown in ensuring firefighters are trained to work with all members of the community, including those with both visible and invisible disabilities.\n",
"o I've seen firsthand how important it is for firefighters to provide inclusive care during medical emergencies. I would be honored to join ______ Fire in continuing to up\n"
]
},
{
"name": "stdout",
"output_type": "stream",
"text": [
"==================================\u001b[1m Ai Message \u001b[0m==================================\n",
"\n",
"{\n",
" \"message\": \"Hi Erika! It's great to meet you. Let's talk about a time when you interacted with someone who had a disability, either in a professional or volunteer role. What was the situation, and how did you approach it?\",\n",
" \"end\": \"no\"\n",
"}\n",
"==================================\u001b[1m Ai Message \u001b[0m==================================\n",
"\n",
"{\n",
" \"message\": \"Thank you for sharing, Erika! Based on your experience as a volunteer firefighter and your training, can you describe a specific instance where you had to adapt your communication or care approach in a situation involving someone with a disability? What was your thought process behind it and how did you ensure they received the help they needed?\",\n",
" \"end\": \"no\"\n",
"}\n"
]
}
],
"source": [
"from langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholder\n",
"current_theme = [x for x in themes if x[\"id\"] == 1][0][\"theme\"]\n",
"theme_context = [x for x in themes if x[\"id\"] == 1][0][\"context\"]\n",
"print(current_theme)\n",
"print(theme_context)\n",
"prompt_template = ChatPromptTemplate.from_messages(\n",
" [\n",
" (\n",
" \"system\",\n",
" f\"\"\"You are a Fire Fighter Interview preparation assistant.\n",
"\n",
"Throughout most Probationary Firefighter Interviews, they will be evaluating a ton of things. Typically, they want to see how you align with the **7 Main Concepts of Firefighting**. They are also watching how nervous you are, your communication skills, and your overall general competence for the role. At the end of the day, you want them to like you.\n",
"\n",
"### 7 Main Concepts:\n",
"- **High Performance Teams**\n",
"- **Situational Awareness**\n",
"- **Being a Great Problem Solver**\n",
"- **Customer Service**\n",
"- **Building Construction, Mechanical Aptitude**\n",
"- **Emergency Medicine Experience**\n",
"- **Mental and Physical Health**\n",
"\n",
"Your crew of four firefighters is usually comprised of a Driver, a Captain, and two firefighters in the back. That is a High-Performance Team. \n",
"\n",
"We are frequently dispatched to calls that require using our understanding of Building Construction Concepts, Mechanical Aptitude, and Emergency Medical Experience. When you respond to an emergency event that is inherently dangerous (like a vehicle fire, a car accident in a slanted ditch, a person trapped under a machine, a house fire, or a chemical suicide), you need to use your Situational Awareness to keep that crew safe. \n",
"\n",
"Sometimes the tools, training, and tactics that you have been taught work perfectly. Sometimes they dont. Can you be a Good Problem Solver to quickly come up with something to make the situation better for the people, places, and environments that we protect?\n",
"\n",
"Ultimately, your crew will be serving the public, and the chiefs need to know that you can be trained to be above their desired standard so that you give the public great Customer Service.\n",
"\n",
"### 20 Important Themes\n",
"Consider the 7 concepts to be the soil. All of your stories grow out of that soil. But not every story works for every question. You need to handpick the right one at the right times to give them. Sort of like how you handpick flowers out of the soil. You NEED to have **20 different flowers** so that you are fully prepared for whatever behavioral question they throw at you. These are the **20 Themes** that you would use for behavioral questions:\n",
"- Customer Service\n",
"- Conflict\n",
"- Challenge\n",
"- Leadership\n",
"- Stress\n",
"- Successful Team\n",
"- Diversity\n",
"- Mistake\n",
"- Unsuccessful Team \n",
"- Disagreement\n",
"- Bent a Rule\n",
"- Delivered a Difficult Message\n",
"- Displayed Integrity\n",
"- Took a Shortcut\n",
"- Didnt Follow the Rules\n",
"- Emergency Response\n",
"- Dealt with Disabilities\n",
"- Solved a Big Problem\n",
"- Continuous Improvement\n",
"- Handled Sensitive Information\n",
"\n",
"### Behavioral Question Starters\n",
"Behavioral questions usually start with phrases like:\n",
"- “Tell me a time when…”\n",
"- “Can you tell me about a time when you…”\n",
"- \"Describe a situation where you had to…\"\n",
"- \"Give me an example of how you…\"\n",
"- \"Have you ever been in a position where you needed to…\"\n",
"- \"Walk me through a time when you…\"\n",
"\n",
"Your goal is to engage in conversation with the user. You will be provided with the current theme, the resume of the user, and example general competency questions and behavioral questions.\n",
"\n",
"\n",
"### STARTPOP Framework\n",
"The STAR Format is what most people tell you to do in order to answer a firefighter interview question. Its a great framework. I highly recommend it. I just advise that you pump it up even further. I call it **STARTPOP**. \n",
"\n",
"Try and pull from different parts of your life. My Chief Training Officer told me that he enjoys candidates that are able to use different experiences to answer the questions. Listening to someone drone on and on about a singular time or type of event in their life is a massive turn-off to the interview panel. Thats a bad thing. Just like most things, variety is the spice of life.\n",
"\n",
"#### Components of STARTPOP:\n",
"1. **Situation**: \n",
" - Set up the answer in the mind of the question asker. \n",
" - Your storytelling skills matter here. It has to be concise and impactful (no more than 25 seconds long).\n",
" - Include dates, ages, places, and circumstances.\n",
"\n",
"2. **Task**: \n",
" - Explain what you needed to do and why you needed to do it.\n",
" - Recap the situation quickly from a different angle.\n",
"\n",
"3. **Actions**: \n",
" - Outline both the negative and the positive way of doing things.\n",
" - Show high moral character in every question.\n",
"\n",
"4. **Results**: \n",
" - Explain what happened as a result of your actions.\n",
" - Share results in a time-specific manner (e.g., “5 months later X happened”).\n",
"\n",
"5. **Transitions**: \n",
" - Speak in a way that aligns with professional expectations.\n",
" - Ensure coherence in your responses.\n",
"\n",
"6. **Personal Lessons**: \n",
" - Discuss what you learned about yourself.\n",
" - Address any concerns the interviewers might have about hiring you.\n",
"\n",
"7. **Other People Observations**: \n",
" - Share insights about others in the situation.\n",
" - Keep it short and to the point.\n",
"\n",
"8. **Professional Connection**: \n",
" - Relate your experience directly to the fire service.\n",
" - Conclude strongly, avoiding phrases like “and so yeah…”.\n",
"\n",
" Current theme {str(current_theme)}\n",
"\n",
" More context about the theme for Creating The Professional Connection (Lessons Learned): {str(theme_context)}\n",
"\n",
" \n",
"\n",
"Your task is to engage the user in conversation, ask relevant questions, that will ultimately help them prepare a strong STARTPOP response based on their experiences and the current theme.\n",
"YOU WILL BE PROVIDED WITH THE USER RESUME, ASK 1 QUESTION AT A TIME AND MAKE IT CONVERSATIONAL AND INTERESTING.\n",
"These responses will be saved and later used to generate a STARTPOP framework by US (DO NOT WORRY ABOUT THAT, WE WILL BE THE ONE TO GENERATE, JUST ENGAGE USER WITH QUESTION AND ANSWER).\n",
"Output format\n",
"\n",
"WILL BE IN JSON\n",
" message:\n",
" end: \"yes\" or \"no\" if you are done with asking questions and confident the responses are okay enough to prepare STARTPOP by us\n",
"\n",
"\"\"\",\n",
" ),\n",
" MessagesPlaceholder(variable_name=\"messages\"),\n",
" ]\n",
")\n",
"\n",
"from langgraph.checkpoint.memory import MemorySaver\n",
"from langgraph.graph import START, MessagesState, StateGraph\n",
"workflow = StateGraph(state_schema=MessagesState)\n",
"\n",
"def call_model(state: MessagesState):\n",
" prompt = prompt_template.invoke(state)\n",
" response = model.invoke(prompt)\n",
" return {\"messages\": response}\n",
"\n",
"\n",
"workflow.add_edge(START, \"model\")\n",
"workflow.add_node(\"model\", call_model)\n",
"\n",
"memory = MemorySaver()\n",
"app = workflow.compile(checkpointer=memory)\n",
"\n",
"\n",
"config = {\"configurable\": {\"thread_id\": \"abc345\"}}\n",
"resume = f\"Resume {str(docs)}\"\n",
"cont = f\"Example general competency and behavioural questions {json.dumps(questions, indent=2)}\"\n",
"input_messages = [HumanMessage(resume)]\n",
"output = app.invoke({\"messages\": input_messages}, config)\n",
"output[\"messages\"][-1].pretty_print()\n",
"\n",
"input_messages = [HumanMessage(cont)]\n",
"output = app.invoke({\"messages\": input_messages}, config)\n",
"output[\"messages\"][-1].pretty_print()"
]
},
{
"cell_type": "code",
"execution_count": 21,
"metadata": {},
"outputs": [],
"source": [
"def format_questions_text(questions_dict,key):\n",
" \"\"\"Format questions as text with dashes.\"\"\"\n",
" formatted_text = \"\"\n",
" for question in questions_dict[key]:\n",
" formatted_text += f\"- {question['question']}\\n\"\n",
" return formatted_text.strip()\n",
"key = 'General Competency Questions'\n",
"formatted_questions = format_questions_text(questions,key)"
]
},
{
"cell_type": "code",
"execution_count": 22,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"'- Why do you want to be a firefighter?\\n- What have you done to prepare for a career in the Fire Service?\\n- Why do you want to work for this department?\\n- Name some of the traits, characteristics, or attributes of a good firefighter.\\n- What are some of the biggest challenges faced by the Fire Service today?\\n- Describe the emergency vs. non-emergency duties of a firefighter.\\n- Where do you see yourself in 1, 5, 10, 20 years?\\n- Describe the chain of command and your role in it.\\n- How do you handle stress, now and once you have the job?\\n- How do you think the role of the firefighter will be different in 5 years?\\n- What is the organizational structure of our Fire Department?\\n- Why do you think honesty and integrity are important in the Fire Service?\\n- What are the advantages and disadvantages of similar vs diverse teams?\\n- List in order of importance: Emergency Response, Public Education, Fire Standards/Enforcement.\\n- What is the most important duty of a firefighter?\\n- What does leadership mean to you?\\n- What do you like most and least about a supervisor?\\n- What do you appreciate in a managers style?\\n- What are the six common leadership styles in the Fire Service?\\n- What do you like most and least about being a firefighter?\\n- How does diversity impact the Fire Service today?\\n- How would you make a positive impact regarding the diversity in the community?\\n- Firefighters work 24-hour shifts. How have you prepared, and what challenges do you think youll face?\\n- Public Education is important in the Fire Service. How would you provide this service?\\n- You are a probationary firefighter. How do you prepare yourself?\\n- Why is respect so important, and what does it mean?\\n- Would you break a rule if asked to?\\n- What are potential sources of workplace conflict? How would you handle workplace conflict?\\n- Why should we hire you?\\n- What are your strengths and weaknesses? (What would your boss say about you?)\\n- How do you want to be remembered at the end of your career?\\n- What skills do you bring to Dispatch?\\n- Walk me through a truck check.\\n- How do you define teamwork in the context of firefighting?\\n- What motivates you to perform well in stressful situations?\\n- Explain how you would handle feedback from a superior, especially if it was critical.\\n- What is your understanding of the core values of the Fire Service?\\n- Describe a time when you demonstrated initiative in the workplace.\\n- How do you prioritize tasks during an emergency response?\\n- What role does technology play in modern firefighting, and how are you prepared for it?\\n- How would you approach learning new skills and techniques required for this job?\\n- Explain how you balance personal and professional commitments in a demanding job.\\n- What strategies do you use to ensure continuous improvement in your work?\\n- How do you approach building trust and relationships within a new team?\\n- What does a day in the life of a firefighter look like for both emergency and non-emergency activities?'"
]
},
"execution_count": 22,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"formatted_questions"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": []
},
{
"cell_type": "code",
"execution_count": 23,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Let's focus on the Customer Service theme first. Can you tell me about a time when you provided exceptional customer service, perhaps in your role as a firefighter or while working at Starbucks? What was the situation like?\n",
"False\n",
"```json\n",
"{\n",
" \"message\": \"That's great to hear! It sounds like you had a positive impact on your customers. Can you share a specific example of a situation where you went above and beyond to ensure a customer had a great experience?\",\n",
" \"end\": \"no\"\n",
"}\n",
"```\n",
"```json\n",
"{\n",
" \"message\": \"That's an excellent approach! Paying attention to detail and proactively asking customers what they need is crucial for great service. Can you tell me about a specific interaction where your attention to detail made a difference for a customer?\",\n",
" \"end\": \"no\"\n",
"}\n",
"```\n",
"```json\n",
"{\n",
" \"message\": \"It seems you did not respond. If you're comfortable, let's continue discussing your customer service experiences. Can you recall a specific situation where your efforts were particularly appreciated by a customer?\",\n",
" \"end\": \"no\"\n",
"}\n",
"```\n",
"```json\n",
"{\n",
" \"message\": \"Hi! How can I assist you today? Are you ready to continue preparing for your firefighter interview?\",\n",
" \"end\": \"no\"\n",
"}\n",
"```\n",
"```json\n",
"{\n",
" \"message\": \"Great! Let's pick up where we left off. Can you share an example of a time you faced a challenge in your firefighting volunteer work? What was the situation, and how did you handle it?\",\n",
" \"end\": \"no\"\n",
"}\n",
"```\n",
"```json\n",
"{\n",
" \"message\": \"It seems you've not responded. If you'd like to continue focusing on your interview preparation, can you tell me about a challenge you faced during your firefighting experience and how you managed it?\",\n",
" \"end\": \"no\"\n",
"}\n",
"```\n",
"```json\n",
"{\n",
" \"message\": \"I see you havent responded. If you need more time or want to discuss a different aspect of your interview preparation, just let me know! Are there any specific topics youd like to cover?\",\n",
" \"end\": \"no\"\n",
"}\n",
"```\n",
"```json\n",
"{\n",
" \"message\": \"It seems we have not connected in a while. If you're ready to continue your interview preparation, or if there's anything specific you'd like to focus on, please let me know!\",\n",
" \"end\": \"no\"\n",
"}\n",
"```\n",
"```json\n",
"{\n",
" \"message\": \"I see you may not be ready to continue right now. Whenever you're ready to resume or if you have any questions, feel free to reach out. I'm here to help!\",\n",
" \"end\": \"no\"\n",
"}\n",
"```\n",
"```json\n",
"{\n",
" \"message\": \"It seems there might have been a typing error. If you have specific questions or topics to cover regarding your interview preparation, please share, and I'll be glad to assist!\",\n",
" \"end\": \"no\"\n",
"}\n",
"```\n",
"```json\n",
"{\n",
" \"message\": \"I see you're not responding right now. Whenever you're ready to continue, just let me know. I'm here to support you with your interview preparation!\",\n",
" \"end\": \"no\"\n",
"}\n",
"```\n",
"```json\n",
"{\n",
" \"message\": \"It seems you might need more time. If you have any questions in the future or want to continue preparing for your interview, feel free to reach out anytime!\",\n",
" \"end\": \"yes\"\n",
"}\n",
"```\n",
"```json\n",
"{\n",
" \"message\": \"Of course! If you need to return for more practice or have questions later, feel free to reach out. Good luck with your interview!\",\n",
" \"end\": \"yes\"\n",
"}\n",
"```\n",
"```json\n",
"{\n",
" \"message\": \"Hi Erika! Let's start preparing your responses for the interview. Can you tell me about a time when you had to deliver a difficult message to a team member or during a situation related to your firefighting volunteer work?\",\n",
" \"end\": \"no\"\n",
"}\n",
"```\n",
"```json\n",
"{\n",
" \"message\": \"It seems there hasnt been a response. If you'd like to continue with your interview preparation, feel free to share a topic or question you'd like to discuss!\",\n",
" \"end\": \"no\"\n",
"}\n",
"```\n",
"```json\n",
"{\n",
" \"message\": \"Hi there! If you're ready to dive back into your interview preparation, just let me know what aspect you'd like to focus on today!\",\n",
" \"end\": \"no\"\n",
"}\n",
"```\n"
]
}
],
"source": [
"import json\n",
"from typing import List, Dict, Optional\n",
"from dataclasses import dataclass\n",
"from pathlib import Path\n",
"from datetime import datetime\n",
"from langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholder\n",
"from langchain_core.messages import HumanMessage, AIMessage\n",
"from langgraph.checkpoint.memory import MemorySaver\n",
"from langgraph.graph import START, MessagesState, StateGraph\n",
"\n",
"@dataclass\n",
"class Message:\n",
" role: str # 'human' or 'ai'\n",
" content: str\n",
" timestamp: str\n",
"\n",
"class FirefighterInterviewAssistant:\n",
" def __init__(self, model, conversation_storage_path: str = \"conversations.json\"):\n",
" \"\"\"\n",
" Initialize the Firefighter Interview Assistant.\n",
" \n",
" Args:\n",
" model: ChatOpenAI model instance\n",
" conversation_storage_path: Path to the JSON file storing conversations\n",
" \"\"\"\n",
" self.storage_path = Path(conversation_storage_path)\n",
" self.current_theme: Optional[Dict] = None\n",
" self.current_resume: Optional[str] = None\n",
" self.model = model\n",
" \n",
" # Initialize storage file if it doesn't exist\n",
" if not self.storage_path.exists():\n",
" self._save_conversations({})\n",
" \n",
" # Initialize LangGraph components\n",
" self.workflow = StateGraph(state_schema=MessagesState)\n",
" self.memory = MemorySaver()\n",
" \n",
" # Set up the prompt template\n",
" self.prompt_template = ChatPromptTemplate.from_messages([\n",
" (\n",
" \"system\",\n",
" f\"\"\"\n",
" You are a Fire Fighter Interview preparation assistant.\n",
"\n",
"Throughout most Probationary Firefighter Interviews, they will be evaluating a ton of things. Typically, they want to see how you align with the **7 Main Concepts of Firefighting**. They are also watching how nervous you are, your communication skills, and your overall general competence for the role. At the end of the day, you want them to like you.\n",
"\n",
"### 7 Main Concepts:\n",
"- **High Performance Teams**\n",
"- **Situational Awareness**\n",
"- **Being a Great Problem Solver**\n",
"- **Customer Service**\n",
"- **Building Construction, Mechanical Aptitude**\n",
"- **Emergency Medicine Experience**\n",
"- **Mental and Physical Health**\n",
"\n",
"Your crew of four firefighters is usually comprised of a Driver, a Captain, and two firefighters in the back. That is a High-Performance Team. \n",
"\n",
"We are frequently dispatched to calls that require using our understanding of Building Construction Concepts, Mechanical Aptitude, and Emergency Medical Experience. When you respond to an emergency event that is inherently dangerous (like a vehicle fire, a car accident in a slanted ditch, a person trapped under a machine, a house fire, or a chemical suicide), you need to use your Situational Awareness to keep that crew safe. \n",
"\n",
"Sometimes the tools, training, and tactics that you have been taught work perfectly. Sometimes they dont. Can you be a Good Problem Solver to quickly come up with something to make the situation better for the people, places, and environments that we protect?\n",
"\n",
"Ultimately, your crew will be serving the public, and the chiefs need to know that you can be trained to be above their desired standard so that you give the public great Customer Service.\n",
"\n",
"### 20 Important Themes\n",
"Consider the 7 concepts to be the soil. All of your stories grow out of that soil. But not every story works for every question. You need to handpick the right one at the right times to give them. Sort of like how you handpick flowers out of the soil. You NEED to have **20 different flowers** so that you are fully prepared for whatever behavioral question they throw at you. These are the **20 Themes** that you would use for behavioral questions:\n",
"- Customer Service\n",
"- Conflict\n",
"- Challenge\n",
"- Leadership\n",
"- Stress\n",
"- Successful Team\n",
"- Diversity\n",
"- Mistake\n",
"- Unsuccessful Team \n",
"- Disagreement\n",
"- Bent a Rule\n",
"- Delivered a Difficult Message\n",
"- Displayed Integrity\n",
"- Took a Shortcut\n",
"- Didnt Follow the Rules\n",
"- Emergency Response\n",
"- Dealt with Disabilities\n",
"- Solved a Big Problem\n",
"- Continuous Improvement\n",
"- Handled Sensitive Information\n",
"\n",
"### Behavioral Question Starters\n",
"Behavioral questions usually start with phrases like:\n",
"- “Tell me a time when…”\n",
"- “Can you tell me about a time when you…”\n",
"- \"Describe a situation where you had to…\"\n",
"- \"Give me an example of how you…\"\n",
"- \"Have you ever been in a position where you needed to…\"\n",
"- \"Walk me through a time when you…\"\n",
"\n",
"Your goal is to engage in conversation with the user. You will be provided with the current theme, the resume of the user, and example general competency questions and behavioral questions.\n",
"\n",
"\n",
"### STARTPOP Framework\n",
"The STAR Format is what most people tell you to do in order to answer a firefighter interview question. Its a great framework. I highly recommend it. I just advise that you pump it up even further. I call it **STARTPOP**. \n",
"\n",
"Try and pull from different parts of your life. My Chief Training Officer told me that he enjoys candidates that are able to use different experiences to answer the questions. Listening to someone drone on and on about a singular time or type of event in their life is a massive turn-off to the interview panel. Thats a bad thing. Just like most things, variety is the spice of life.\n",
"\n",
"#### Components of STARTPOP:\n",
"1. **Situation**: \n",
" - Set up the answer in the mind of the question asker. \n",
" - Your storytelling skills matter here. It has to be concise and impactful (no more than 25 seconds long).\n",
" - Include dates, ages, places, and circumstances.\n",
"\n",
"2. **Task**: \n",
" - Explain what you needed to do and why you needed to do it.\n",
" - Recap the situation quickly from a different angle.\n",
"\n",
"3. **Actions**: \n",
" - Outline both the negative and the positive way of doing things.\n",
" - Show high moral character in every question.\n",
"\n",
"4. **Results**: \n",
" - Explain what happened as a result of your actions.\n",
" - Share results in a time-specific manner (e.g., “5 months later X happened”).\n",
"\n",
"5. **Transitions**: \n",
" - Speak in a way that aligns with professional expectations.\n",
" - Ensure coherence in your responses.\n",
"\n",
"6. **Personal Lessons**: \n",
" - Discuss what you learned about yourself.\n",
" - Address any concerns the interviewers might have about hiring you.\n",
"\n",
"7. **Other People Observations**: \n",
" - Share insights about others in the situation.\n",
" - Keep it short and to the point.\n",
"\n",
"8. **Professional Connection**: \n",
" - Relate your experience directly to the fire service.\n",
" - Conclude strongly, avoiding phrases like “and so yeah…”.\n",
" Current theme with More context about the theme for Creating The Professional Connection (Lessons Learned): {self.current_theme}\n",
" \n",
"Sample General Competency QUESTIONS and Situational Questions: {format_questions_text(questions,'General Competency Questions')}\n",
"Sample Situational Questions: {format_questions_text(questions,'Situational Questions')}\n",
"\n",
"Your task is to engage the user in conversation, ask relevant questions, that will ultimately help them prepare a strong STARTPOP response based on their experiences and the current theme.\n",
"YOU WILL BE PROVIDED WITH THE USER RESUME, ASK 1 QUESTION AT A TIME AND MAKE IT CONVERSATIONAL AND INTERESTING.\n",
"These responses will be saved and later used to generate a STARTPOP framework by US (DO NOT WORRY ABOUT THAT, WE WILL BE THE ONE TO GENERATE, JUST ENGAGE USER WITH QUESTION AND ANSWER).\n",
"Output format\n",
"\n",
"WILL BE IN JSON, avoid puttting ```json, before or after , return the excat json with nothing else\n",
" message:\n",
" end: \"yes\" or \"no\" if you are done with asking questions and confident the responses are okay enough to prepare STARTPOP by us\n",
"NOTE: DO NOT KEEP THE CONVERSATION , CAREFULL ANALYZE USER RESUME AND THE PROVIDED EXAMPLES QUESTIONS AND ALL CONTEXT , ASK RELEVANT QUESTION BASED ON THE THEME AND THAT IS ALL \n",
"\"\"\"\n",
" ),\n",
" MessagesPlaceholder(variable_name=\"messages\")\n",
" ])\n",
" \n",
" # Set up LangGraph workflow\n",
" self._setup_workflow()\n",
"\n",
" def _setup_workflow(self):\n",
" \"\"\"Setup LangGraph workflow\"\"\"\n",
" def call_model(state: MessagesState):\n",
" prompt = self.prompt_template.invoke(state)\n",
" response = self.model.invoke(prompt)\n",
" return {\"messages\": response}\n",
"\n",
" self.workflow.add_edge(START, \"model\")\n",
" self.workflow.add_node(\"model\", call_model)\n",
" self.app = self.workflow.compile(checkpointer=self.memory)\n",
"\n",
" def _convert_to_langchain_messages(self, messages: List[Message]) -> List[HumanMessage | AIMessage]:\n",
" \"\"\"Convert our Message objects to LangChain message objects\"\"\"\n",
" converted_messages = []\n",
" for msg in messages:\n",
" if msg.role == \"human\":\n",
" converted_messages.append(HumanMessage(content=msg.content))\n",
" else:\n",
" converted_messages.append(AIMessage(content=msg.content))\n",
" return converted_messages\n",
"\n",
" def start_conversation(self, conversation_id: str, resume: str, theme: Dict) -> Dict:\n",
" \"\"\"\n",
" Start a new conversation or load an existing one.\n",
" \"\"\"\n",
" self.current_conversation_id = conversation_id\n",
" self.current_resume = resume\n",
" self.current_theme = theme\n",
" \n",
" # Initialize conversation in storage\n",
" conversations = self._load_conversations()\n",
" if conversation_id not in conversations:\n",
" conversations[conversation_id] = {\n",
" \"resume\": resume,\n",
" \"theme\": theme,\n",
" \"messages\": []\n",
" }\n",
" self._save_conversations(conversations)\n",
" \n",
" # Initialize conversation with resume\n",
" config = {\"configurable\": {\"thread_id\": conversation_id}}\n",
" input_messages = [HumanMessage(content=f\"Resume: {resume}\")]\n",
" output = self.app.invoke({\"messages\": input_messages}, config)\n",
" \n",
" # Parse and store initial response\n",
" response = self._parse_ai_response(output[\"messages\"][-1].content)\n",
" self.add_message(\"ai\", response[\"message\"])\n",
" \n",
" return response\n",
"\n",
" def process_user_response(self, user_message: str) -> Dict:\n",
" \"\"\"\n",
" Process user response and generate AI response.\n",
" \"\"\"\n",
" # Add user message to conversation\n",
" self.add_message(\"human\", user_message)\n",
" \n",
" # Get conversation history and convert to LangChain messages\n",
" history = self.get_conversation_history()\n",
" messages = self._convert_to_langchain_messages(history)\n",
" \n",
" # Generate response using LangGraph\n",
" config = {\"configurable\": {\"thread_id\": self.current_conversation_id}}\n",
" output = self.app.invoke({\"messages\": messages}, config)\n",
" \n",
" # Parse and store AI response\n",
" response = self._parse_ai_response(output[\"messages\"][-1].content)\n",
" self.add_message(\"ai\", response[\"message\"])\n",
" \n",
" return response\n",
"\n",
" def _parse_ai_response(self, content: str) -> Dict:\n",
" \"\"\"Parse AI response content into expected format\"\"\"\n",
" try:\n",
" response = json.loads(content)\n",
" return {\n",
" \"message\": response.get(\"message\", \"\"),\n",
" \"end\": response.get(\"end\", \"no\") == \"yes\"\n",
" }\n",
" except json.JSONDecodeError:\n",
" return {\n",
" \"message\": content,\n",
" \"end\": False\n",
" }\n",
"\n",
" def add_message(self, role: str, content: str) -> None:\n",
" \"\"\"Add a message to the conversation history\"\"\"\n",
" if not hasattr(self, 'current_conversation_id'):\n",
" raise ValueError(\"No active conversation. Call start_conversation first.\")\n",
" \n",
" message_data = {\n",
" \"role\": role,\n",
" \"content\": content,\n",
" \"timestamp\": datetime.now().isoformat()\n",
" }\n",
" \n",
" conversations = self._load_conversations()\n",
" conversations[self.current_conversation_id][\"messages\"].append(message_data)\n",
" self._save_conversations(conversations)\n",
"\n",
" def get_conversation_history(self, conversation_id: Optional[str] = None) -> List[Message]:\n",
" \"\"\"Get the conversation history\"\"\"\n",
" conv_id = conversation_id or self.current_conversation_id\n",
" if not conv_id:\n",
" raise ValueError(\"No conversation ID provided or active\")\n",
" \n",
" conversations = self._load_conversations()\n",
" if conv_id not in conversations:\n",
" raise ValueError(f\"Conversation {conv_id} not found\")\n",
" \n",
" return [\n",
" Message(\n",
" role=msg[\"role\"],\n",
" content=msg[\"content\"],\n",
" timestamp=msg[\"timestamp\"]\n",
" )\n",
" for msg in conversations[conv_id][\"messages\"]\n",
" ]\n",
"\n",
" def _load_conversations(self) -> Dict:\n",
" \"\"\"Load conversations from storage file\"\"\"\n",
" try:\n",
" with open(self.storage_path, 'r') as f:\n",
" return json.load(f)\n",
" except FileNotFoundError:\n",
" return {}\n",
"\n",
" def _save_conversations(self, conversations: Dict) -> None:\n",
" \"\"\"Save conversations to storage file\"\"\"\n",
" with open(self.storage_path, 'w') as f:\n",
" json.dump(conversations, f, indent=2)\n",
"\n",
"\n",
"\n",
"from langchain_openai import ChatOpenAI\n",
"model = ChatOpenAI(model=\"gpt-4o-mini\")\n",
"\n",
"# Initialize the assistant\n",
"assistant = FirefighterInterviewAssistant(model)\n",
"\n",
"# Start a new conversation\n",
"theme = themes[0]\n",
"response = assistant.start_conversation(\n",
" conversation_id=\"user123\",\n",
" resume=f\"Resume {docs}\",\n",
" theme=theme\n",
")\n",
"\n",
"print(response[\"message\"]) # Initial AI question\n",
"print(response[\"end\"]) # Conversation status\n",
"\n",
"# Process user response\n",
"while not response[\"end\"]:\n",
" user_input = input(\"Your response: \")\n",
" response = assistant.process_user_response(user_input)\n",
" print(response[\"message\"])\n",
"\n",
"\n",
"\n",
"\n",
"\n",
"\n",
"\n",
" "
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": []
},
{
"cell_type": "code",
"execution_count": 11,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"[{'id': 1,\n",
" 'theme': 'Disability Questions',\n",
" 'context': \"Firefighters respond to lots of medical calls, many of which involve visible and invisible disabilities.\\n- It's critical to be aware of the unique needs of people with physical health issues and mental health challenges.\\n- Firefighters must provide compassionate care to everyone and giving respect to all regardless of their abilities.\\n- As first responders, firefighters are often the first point of contact for vulnerable individuals, and how they interact can make a lasting impact on the persons well-being.\\n- Firefighters should be well-trained to recognize different disabilities and adapt their approach to ensure effective communication and assistance, especially for those with cognitive or sensory impairments.\\n- This requires empathy, patience, and a strong understanding of mental health and physical disabilities, along with the proper use of equipment and techniques to ensure safety and dignity for everyone involved.\\n- Potential Conclusions:\\no I know that ______ Fire has a strong reputation for responding with compassion and professionalism to individuals with disabilities, ensuring that they feel respected and supported during emergencies.\\no I admire the commitment that ______ Fire has shown in ensuring firefighters are trained to work with all members of the community, including those with both visible and invisible disabilities.\\no I've seen firsthand how important it is for firefighters to provide inclusive care during medical emergencies. I would be honored to join ______ Fire in continuing to up\"},\n",
" {'id': 2,\n",
" 'theme': 'Leadership Skills Questions',\n",
" 'context': \"Leadership is not about having authority; it's about inspiring others to reach their full potential.\\n- Effective leaders lead by example, demonstrating integrity, accountability, and a commitment to teamwork.\\n- In the fire service, leadership is not confined to rank; every firefighter has the opportunity to lead and contribute to the success of the team.\\n- Adaptability and decisiveness are crucial qualities in leadership, especially in high-stress and rapidly changing environments.\\n- Leadership is also about fostering a culture of continuous learning and improvement, encouraging feedback, and promoting innovation.\\n- Potential Conclusions:\\no I've heard about the emphasis on leadership development within ______ Fire, and it's clear that the department values cultivating leaders at all levels. I'm eager to contribute to that culture and continue growing as a leader.\\no During my station visit, I observed how firefighters at ______ Fire take initiative and support each other, regardless of rank. That collaborative leadership approach is something I aspire to emulate and contribute to.\\no I've learned that leadership in the fire service is not just about giving orders; it's about empowering others, building trust, and fostering a sense of unity within the team. I'm excited about the opportunity to lead by example and positively influence my fellow firefighters at ______ Fire.\"},\n",
" {'id': 3,\n",
" 'theme': 'Conflict Questions',\n",
" 'context': 'Conflict is a huge problem in high performing teams.\\n- Creates a poisonous work environment, reduces efficiencies, and creates mental health issues.\\n- Those are serious issues and must be addressed as soon as they pop up.\\n- One of the best ways to address it through increasing the communication and giving people an opportunity to explain their opinions or viewpoints.\\n- I tend to think about the three Ts (teamwork, training and trust) and how important it is to fall back on those.\\n- Attempt to secure behaviour modification through voluntary compliance.\\n- Potential Conclusions:\\no I know that professionalism runs through the entire department here. ______\\no Firefighters are professional and committed to safe and respectful workplaces.\\no One thing about the fire service is that you all do a great job of communicating and creating a chain of command to help simplify complex problems\\no Its important to remember the values of the fire service and keep those in mind whenever conflicts arise.\\no Tie in stats and figures from your research on the department.'},\n",
" {'id': 4,\n",
" 'theme': 'Stress Questions',\n",
" 'context': 'My big takeaway is that stress is everywhere, and it affects everyone in different ways.\\n- The amount of mental health issues and stress levels are up exponentially with the community.\\n- Especially when you factor in the effects of COVID-19 and the lockdowns.\\n- That _________ situation made me realize that we must be supportive of one another and reduce the stigma.\\n- Potential Conclusions:\\no I know that the team members at _______ Fire are exposed to stressful situations on a regular basis, and it is critical that they be supportive to one another in order to maintain a strong team.\\no I have spoken to ______ about your mental health programs and can see that you really take the time to pour into each of your firefighters cup. I really admire that.\\no I looked into that _________ program that your department us'},\n",
" {'id': 5,\n",
" 'theme': 'Emergency Questions',\n",
" 'context': 'Emergencies can happen anywhere at anytime.\\n- Usually with little to no warning.\\n- During those times people fall back onto their training and most commonly practiced strategies.\\n- We need to ensure that our personnel are available and ready to answer the call whenever that happens in the community, and they are using the most effective strategies and techniques possible.\\n- Potential Conclusions:\\no I know that the expectation of _______ Fire is to train at least 2-3 hours per shift.\\no That works out to 14-21 hours per month. When you factor in running calls in between those training sessions there is a fair bit of opportunity for Firefighters to become very good at their jobs and be fully prepared.\\no Consistent commitment to training everything from the basics up to the complicated things 2-3 hours per shift is what makes the people on _____ Fire so good at their job.'},\n",
" {'id': 6,\n",
" 'theme': 'Mistake',\n",
" 'context': 'We all make mistakes. It is okay to make them. But it is not okay to not learn from them.\\n- Mistakes are just proof that you are trying your best.\\n- They are an opportunity for growth and for development.\\n- They are the things that help sharpen the knives in a drawer.\\n- The key is not to make the same mistake twice.\\n- Potential Conclusions:\\no I am certain that _______ Firefighters conduct regular follow-ups after calls.\\no Its important for everyone to check their ego and be accountable for the things they messed up on.\\no I know that Chief ______ promotes an open and transparent environment. He/She is not afraid to admit when they made a mistake. So, it is important for everyone in the department to follow suit.'},\n",
" {'id': 7,\n",
" 'theme': 'Cultural, Diversity, and Inclusion Questions',\n",
" 'context': 'Communities are becoming more and more diverse everyday. It is important for the Fire Service to recognize that.\\n- Steps can be taken every single day to create an environment that is inclusive and open to everyone regardless of their background, language, abilities, or self-identification.\\n- Public servants serve the public.\\n- No passing judgement on people. No racism, no homophobia, no misogyny.\\n- Treat everyone with respect and educate ourselves about the differences in our communities.\\n- Potential Conclusions:\\no ______ Fire is very professional and respectful. I have only seen and heard good things about how much of a concerted effort you are making to be more inclusive.\\no I spent some time looking at the Public Education pamphlets at station _____ and saw that they were offered in a bunch of different languages. That was amazing and I really think that shows the community how much you care about reducing the barriers to safety.\\no I spoke with _____ and learned about how enjoyable of an experience they have had working on your departmen'},\n",
" {'id': 8,\n",
" 'theme': 'Customer Service Questions',\n",
" 'context': 'Providing great customer service really just requires caring about people and trying to always make things better than you found it.\\n- Our communities are better served when they have people that are willing to sacrifice their time and energy.\\n- I personally enjoy going to places and working with people that provide great customer service. I would only expect that to be the level of service provided by firefighters.\\n- Potential Conclusions:\\no You cant train people to care and its important for the fire service to hire people who innately have a desire to go the extra mile. It has to be in their DNA.\\no I know that _____ Fire has done a great job finding lots of those types of people and they constantly work towards fostering that characteristic in everyone brought into the organization.\\no Firefighters go above and beyond every shift. Its our job to serve the community and protect life, property'},\n",
" {'id': 9,\n",
" 'theme': 'Successful and Unsuccessful Team Questions',\n",
" 'context': 'Teamwork is necessary to assist in overcoming emergencies. Especially expanding ones. I understand how chain of commands works and the importance of monitoring the span of control as well.\\n- Great teamwork creates synergy in the workplace and makes environments happier, healthier, and safer.\\n- There is no “I” in team.\\n- All tasks are important no matter how big or small it may seem.\\n- Great teams are built by people that are committed to training and knowing their roles well.\\n- Need to train in order to create muscle memory and prevent “skills fade”\\n- Potential Conclusions:\\no I know that Firefighting is a team sport and that _____ Fire does a great job in fostering that camaraderie.\\no I have seen the _____ Fire team play in _____ tournament and know that you guys applaud crews bonding over meals at the station.\\no I really appreciate the fact that you allow crews to train together and share insights learned across the department so that everyone gets better all the time.\\no Include stats and figures, following SOPs and safety protocols into the answer'},\n",
" {'id': 10,\n",
" 'theme': 'Disagree with a Supervisor Questions',\n",
" 'context': 'Disagreements can and will happen but what matters is that the issues are addressed in a respectful and professional manner.\\n- I always recommend doing them in a private and non-confrontational manner\\n- With a focus on finding acceptable solutions that can be implemented effectively.\\n- The idea is to not let things linger and harbour because that creates a poisonous work environment.\\n- Potential Conclusions:\\no I understand my role in the chain of command and will always try my best to follow orders as they are given. But whenever a disagreement may come up it is important to show respect and listen to all sides.\\no _____ Fire works hard to promote captains and chiefs that are smart, capable and proven leaders. It is important to acknowledge that every time there is a potential disagreement. They may see things that I am not aware of.\\no _____ Fire works hard to minimize the number of disagreements in the workplace.'},\n",
" {'id': 11,\n",
" 'theme': 'Rule Bending',\n",
" 'context': 'I do not bend rules that jeopardize health and safety or rules that test my ethics and morality.\\n- I know that the fire service has that same perspective.\\n- Therefore, all organizations need to have rules and all people in those organizations need to know them.\\n- This is why there are internal SOPs, OHSA, HTA, Fire Code, Criminal Code etc.\\n- Potential Conclusions:\\no I know that _____ Fire has a robust SOP package, and it is part of the training process for every new hire to go through them and get schooled up on the importance of them.\\no The onus is on me to spend time learning the ins and outs of this organization if I am blessed with the opportunity to work here.\\no Firefighters need to be rule followers. It is an inherently dangerous job and freelancing has no part o.'},\n",
" {'id': 12,\n",
" 'theme': 'Integrity Challenge Questions',\n",
" 'context': 'Integrity is the cornerstone of the fire service profession, guiding every action and decision.\\n- Firefighters are entrusted with public safety, making it imperative to uphold the highest ethical standards.\\n- In the fire service, we are governed by regulations such as the NFPA standards and the Ontario FPPA, which mandate strict compliance to ensure safety and well-being.\\n- These guidelines underscore the need for transparency and ethical conduct in all our actions.\\n- Potential Conclusions:\\no Integrity is not just a personal attribute; it is a professional necessity that ensures the effectiveness and reliability of our fire service operations.\\no When faced with an integrity challenge, it is essential to remain steadfast in ethical principles, even under pressure.\\no This experience reinforced my commitment to the values of the fire service and highlighted the importance of fostering a culture where integrity is paramount.\\no By upholding these standards, we not only protect ourselves and our colleagues but also maintain the trust and confidence of the communities we serve.'},\n",
" {'id': 13,\n",
" 'theme': 'Taking a Shortcut at work',\n",
" 'context': \"I believe in having strong work ethic. I was raised that way and my work experience to date proves that…\\n- I definitely do not take shortcuts around things that compromise health and safety or my ethics and morality.\\n- I never take shortcuts that compromise the health and safety of myself or others, or that challenge my ethical and moral values.\\n- I believe that the fire service shares this same perspective, prioritizing safety, ethics, and morality above all else.\\n- In my view, all organizations should establish clear rules, and it is essential for every member of those organizations to be aware of and follow these rules.\\n- This is why organizations have internal Standard Operating Procedures (SOPs), Occupational Health and Safety Act (OHSA) guidelines, Highway Traffic Act (HTA) regulations, Fire Codes, and even the Criminal Code when necessary.\\n- Potential Conclusions:\\no I'm aware that at _____ Fire, they have a comprehensive set of Standard Operating Procedures (SOPs) that are diligently followed. During my training, I learned about the critical importance of these procedures and the reasons for adhering to them.\\no If I were fortunate enough to join this organization, I understand that it would be my responsibility to thoroughly acquaint myself with its rules and procedures. I'm committed to investing the necessary time and effort to ensure I comply with them.\\no In firefighting, there's no room for shortcuts. It's an inherently perilous job and deviating from established procedures can jeopardize lives. Rules are not just guidelines but safeguards that protect everyone and ensure a safe return from each mission.\"},\n",
" {'id': 14,\n",
" 'theme': 'Delivering Difficult Messages',\n",
" 'context': \"I do not shy away from the responsibility of delivering difficult messages when necessary, even though it may be uncomfortable. My commitment to honesty and ethical conduct remains unwavering.\\n- I believe that the fire service, like any responsible organization, understands the importance of addressing challenging issues head-on, which aligns with my perspective on this matter.\\n- In all organizations, there should be clear protocols and guidelines for delivering difficult messages effectively and sensitively, ensuring that the message is conveyed while respecting the dignity and feelings of the recipients.\\n- This is why organizations often have established procedures and communication guidelines to handle such situations professionally and ethically.\\n- Potential Conclusions:\\no I'm aware that at _____ Fire, they prioritize open and honest communication. During my training, I learned about their approach to delivering difficult messages and the importance of doing so with empathy and professionalism.\\no If I were part of this organization, I would understand that delivering difficult messages might be a part of my role. I would be committed to following their established protocols and guidelines for addressing such situations.\\no In firefighting and similar high-stakes professions, effective communication, even in challenging circumstances, can be a matter of life and death. The rules and procedures in place are not just about following a script but ensuring that messages are conveyed in a way that respects the emotions and well-being of all involved parties.\"},\n",
" {'id': 15,\n",
" 'theme': 'Not Following SOPs/SOGs',\n",
" 'context': \"I have never deviated from established SOPs at work, as doing so can compromise safety, ethical standards, and the integrity of the organization.\\n- I understand that the fire service, like any responsible organization, places a high value on adherence to SOPs, which is consistent with my perspective.\\n- In every organization, it's crucial to have clear and well-documented SOPs that every member understands and follows. This ensures consistency, safety, and ethical conduct.\\n- This is why organizations implement internal SOPs and adhere to external regulations like OHSA, HTA, and Fire Codes to maintain high standards of operation.\\n- Potential conclusions:\\no I'm aware that at _____ Fire, strict adherence to SOPs is fundamental to their operational success. During my training, I gained a deep appreciation for the importance of following these procedures and the consequences of not doing so.\\no If I were to become part of this organization, I would fully understand the gravity of following SOPs. I would uphold these standards and would actively seek training and support to ensure compliance.\\no In firefighting and similar high-risk professions, disregarding SOPs is simply not an option. These procedures are in place to protect lives and property. Any deviation can have serious consequences, and rule adherence is non-negotiable.\"},\n",
" {'id': 16,\n",
" 'theme': 'Continuous Improvement',\n",
" 'context': \"Continuous improvement is about striving to be better every day, both as an individual and as part of a team.\\n- I believe that the fire service embodies this concept by constantly evolving through training, adopting new technologies, and learning from past experiences.\\n- Reflecting on one's performance and seeking feedback are essential components of continuous improvement, as they help identify strengths and areas for growth.\\n- Staying updated with new firefighting techniques, equipment, and regulations is crucial for maintaining effectiveness and safety in the field.\\n- Potential Conclusions:\\no I've seen how ______ Fire prioritizes ongoing training and professional development to ensure its firefighters remain at the forefront of the profession. I look forward to being part of an organization that values growth and innovation.\\no During my station visit, I was impressed by the emphasis on learning and improvement at ______ Fire. That environment aligns perfectly with my personal commitment to always better myself and support my team in doing the same.\\no I believe continuous improvement is not just about improving skills but also about fostering a culture where everyone strives to do better. At ______ Fire, Im eager to contribute to that culture by embracing challenges, seeking feedback, and pursuing opportunities for growth.\"},\n",
" {'id': 17,\n",
" 'theme': 'Handling Sensitive Information',\n",
" 'context': 'Firefighters are often entrusted with sensitive information, whether it pertains to medical calls, emergency incidents, or personal details about community members.\\n- Maintaining confidentiality and discretion is critical for preserving trust and ensuring the dignity of individuals involved.\\n- Handling sensitive information responsibly requires understanding and adhering to organizational policies, as well as exercising sound judgment.\\n- Respecting privacy is a key component of professionalism, especially in a role as visible and impactful as firefighting.\\n- Potential Conclusions:\\no I understand that ______ Fire has clear guidelines and training around handling sensitive information. I respect and appreciate the importance of these protocols and would adhere to them without compromise.\\no If given the opportunity to join ______ Fire, I would uphold the highest standards of confidentiality and discretion, ensuring that sensitive information is treated with the respect it deserves.\\no Handling sensitive information with care is essential to maintaining the trust of the community and the integrity of the fire service. Im committed to embodying these values and ensuring that all information is managed professionally and ethically.'},\n",
" {'id': 18,\n",
" 'theme': 'Solving a Problem',\n",
" 'context': \"I believe problem-solving is one of the most valuable skills in the fire service, as it often determines the success or failure of a critical situation.\\n- Effective problem-solving requires a clear assessment of the situation, evaluating available resources, and making informed decisions quickly.\\n- Firefighting often involves scenarios where unexpected challenges arise, and the ability to stay calm and address issues methodically is essential.\\n- Collaboration is a significant part of problem-solving, as no one firefighter has all the answers. Solutions come from teamwork and leveraging everyone's strengths.\\n- Potential Conclusions:\\no I understand that ______ Fire emphasizes critical thinking and problem-solving in their training programs. During my training, I honed these skills and learned how to approach challenges systematically and effectively.\\no If I were part of ______ Fire, I would actively apply my problem-solving abilities in both emergency and non-emergency situations, ensuring I work collaboratively with my team to find the best outcomes.\\no Solving problems in firefighting goes beyond emergencies; it's about addressing challenges proactively, whether it's equipment maintenance, community outreach, or operational efficiency. I'm committed to contributing to this problem-solving culture at ______ Fire.\"},\n",
" {'id': 19,\n",
" 'theme': 'Challenge Questions',\n",
" 'context': 'Life is full of challenges. It is important for firefighters to be the type of people that take those challenges head on and constantly work to find ways to overcome them.\\n- Grit, persistence, creative problem solving, and strong mental health are the keys to overcoming challenges.\\n- Life can change in a second. Its important to be adaptive and flexible.\\n- Potential Conclusions:\\no And I am certain that ______ Fire works very hard to meet every challenge and then overcome them.\\no I think about how you guys handled the ________ situation\\no or the recent fire at _______\\no and as an outsider looking in, I was thoroughly impressed with the way the department handled it.'}]"
]
},
"execution_count": 11,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"themes"
]
},
{
"cell_type": "code",
"execution_count": 8,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Hi Erika! Let's start preparing you for that interview. Can you tell me about a time when you had to deal with a difficult situation as a volunteer firefighter? What was the situation and how did you handle it?\n",
"False\n"
]
},
{
"ename": "TypeError",
"evalue": "Message.__init__() got an unexpected keyword argument 'additional_kwargs'",
"output_type": "error",
"traceback": [
"\u001b[0;31m---------------------------------------------------------------------------\u001b[0m",
"\u001b[0;31mTypeError\u001b[0m Traceback (most recent call last)",
"Cell \u001b[0;32mIn[8], line 323\u001b[0m\n\u001b[1;32m 321\u001b[0m \u001b[38;5;28;01mwhile\u001b[39;00m \u001b[38;5;129;01mnot\u001b[39;00m response[\u001b[38;5;124m\"\u001b[39m\u001b[38;5;124mend\u001b[39m\u001b[38;5;124m\"\u001b[39m]:\n\u001b[1;32m 322\u001b[0m user_input \u001b[38;5;241m=\u001b[39m \u001b[38;5;28minput\u001b[39m(\u001b[38;5;124m\"\u001b[39m\u001b[38;5;124mYour response: \u001b[39m\u001b[38;5;124m\"\u001b[39m)\n\u001b[0;32m--> 323\u001b[0m response \u001b[38;5;241m=\u001b[39m \u001b[43massistant\u001b[49m\u001b[38;5;241;43m.\u001b[39;49m\u001b[43mprocess_user_response\u001b[49m\u001b[43m(\u001b[49m\u001b[43muser_input\u001b[49m\u001b[43m)\u001b[49m\n\u001b[1;32m 324\u001b[0m \u001b[38;5;28mprint\u001b[39m(response[\u001b[38;5;124m\"\u001b[39m\u001b[38;5;124mmessage\u001b[39m\u001b[38;5;124m\"\u001b[39m])\n",
"Cell \u001b[0;32mIn[8], line 224\u001b[0m, in \u001b[0;36mFirefighterInterviewAssistant.process_user_response\u001b[0;34m(self, user_message)\u001b[0m\n\u001b[1;32m 219\u001b[0m \u001b[38;5;28mself\u001b[39m\u001b[38;5;241m.\u001b[39madd_message(\u001b[38;5;124m\"\u001b[39m\u001b[38;5;124mhuman\u001b[39m\u001b[38;5;124m\"\u001b[39m, user_message)\n\u001b[1;32m 221\u001b[0m \u001b[38;5;66;03m# Prepare messages for model\u001b[39;00m\n\u001b[1;32m 222\u001b[0m messages \u001b[38;5;241m=\u001b[39m [HumanMessage(content\u001b[38;5;241m=\u001b[39mmsg\u001b[38;5;241m.\u001b[39mcontent) \u001b[38;5;28;01mif\u001b[39;00m msg\u001b[38;5;241m.\u001b[39mrole \u001b[38;5;241m==\u001b[39m \u001b[38;5;124m\"\u001b[39m\u001b[38;5;124mhuman\u001b[39m\u001b[38;5;124m\"\u001b[39m \n\u001b[1;32m 223\u001b[0m \u001b[38;5;28;01melse\u001b[39;00m AIMessage(content\u001b[38;5;241m=\u001b[39mmsg\u001b[38;5;241m.\u001b[39mcontent) \n\u001b[0;32m--> 224\u001b[0m \u001b[38;5;28;01mfor\u001b[39;00m msg \u001b[38;5;129;01min\u001b[39;00m \u001b[38;5;28;43mself\u001b[39;49m\u001b[38;5;241;43m.\u001b[39;49m\u001b[43mget_conversation_history\u001b[49m\u001b[43m(\u001b[49m\u001b[43m)\u001b[49m]\n\u001b[1;32m 226\u001b[0m \u001b[38;5;66;03m# Generate response using LangGraph\u001b[39;00m\n\u001b[1;32m 227\u001b[0m config \u001b[38;5;241m=\u001b[39m {\u001b[38;5;124m\"\u001b[39m\u001b[38;5;124mconfigurable\u001b[39m\u001b[38;5;124m\"\u001b[39m: {\u001b[38;5;124m\"\u001b[39m\u001b[38;5;124mthread_id\u001b[39m\u001b[38;5;124m\"\u001b[39m: \u001b[38;5;28mself\u001b[39m\u001b[38;5;241m.\u001b[39mcurrent_conversation_id}}\n",
"Cell \u001b[0;32mIn[8], line 282\u001b[0m, in \u001b[0;36mFirefighterInterviewAssistant.get_conversation_history\u001b[0;34m(self, conversation_id)\u001b[0m\n\u001b[1;32m 279\u001b[0m \u001b[38;5;28;01mif\u001b[39;00m conv_id \u001b[38;5;129;01mnot\u001b[39;00m \u001b[38;5;129;01min\u001b[39;00m conversations:\n\u001b[1;32m 280\u001b[0m \u001b[38;5;28;01mraise\u001b[39;00m \u001b[38;5;167;01mValueError\u001b[39;00m(\u001b[38;5;124mf\u001b[39m\u001b[38;5;124m\"\u001b[39m\u001b[38;5;124mConversation \u001b[39m\u001b[38;5;132;01m{\u001b[39;00mconv_id\u001b[38;5;132;01m}\u001b[39;00m\u001b[38;5;124m not found\u001b[39m\u001b[38;5;124m\"\u001b[39m)\n\u001b[0;32m--> 282\u001b[0m \u001b[38;5;28;01mreturn\u001b[39;00m [\n\u001b[1;32m 283\u001b[0m Message(\u001b[38;5;241m*\u001b[39m\u001b[38;5;241m*\u001b[39mmsg) \u001b[38;5;28;01mfor\u001b[39;00m msg \u001b[38;5;129;01min\u001b[39;00m conversations[conv_id][\u001b[38;5;124m\"\u001b[39m\u001b[38;5;124mmessages\u001b[39m\u001b[38;5;124m\"\u001b[39m]\n\u001b[1;32m 284\u001b[0m ]\n",
"Cell \u001b[0;32mIn[8], line 283\u001b[0m, in \u001b[0;36m<listcomp>\u001b[0;34m(.0)\u001b[0m\n\u001b[1;32m 279\u001b[0m \u001b[38;5;28;01mif\u001b[39;00m conv_id \u001b[38;5;129;01mnot\u001b[39;00m \u001b[38;5;129;01min\u001b[39;00m conversations:\n\u001b[1;32m 280\u001b[0m \u001b[38;5;28;01mraise\u001b[39;00m \u001b[38;5;167;01mValueError\u001b[39;00m(\u001b[38;5;124mf\u001b[39m\u001b[38;5;124m\"\u001b[39m\u001b[38;5;124mConversation \u001b[39m\u001b[38;5;132;01m{\u001b[39;00mconv_id\u001b[38;5;132;01m}\u001b[39;00m\u001b[38;5;124m not found\u001b[39m\u001b[38;5;124m\"\u001b[39m)\n\u001b[1;32m 282\u001b[0m \u001b[38;5;28;01mreturn\u001b[39;00m [\n\u001b[0;32m--> 283\u001b[0m \u001b[43mMessage\u001b[49m\u001b[43m(\u001b[49m\u001b[38;5;241;43m*\u001b[39;49m\u001b[38;5;241;43m*\u001b[39;49m\u001b[43mmsg\u001b[49m\u001b[43m)\u001b[49m \u001b[38;5;28;01mfor\u001b[39;00m msg \u001b[38;5;129;01min\u001b[39;00m conversations[conv_id][\u001b[38;5;124m\"\u001b[39m\u001b[38;5;124mmessages\u001b[39m\u001b[38;5;124m\"\u001b[39m]\n\u001b[1;32m 284\u001b[0m ]\n",
"\u001b[0;31mTypeError\u001b[0m: Message.__init__() got an unexpected keyword argument 'additional_kwargs'"
]
}
],
"source": [
"import json\n",
"from typing import List, Dict, Optional\n",
"from dataclasses import dataclass\n",
"from pathlib import Path\n",
"from langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholder\n",
"from langchain_core.messages import HumanMessage, AIMessage\n",
"from langgraph.checkpoint.memory import MemorySaver\n",
"from langgraph.graph import START, MessagesState, StateGraph\n",
"\n",
"@dataclass\n",
"class Message:\n",
" role: str # 'human' or 'ai'\n",
" content: str\n",
" timestamp: str\n",
"\n",
"class FirefighterInterviewAssistant:\n",
" def __init__(self, model, conversation_storage_path: str = \"conversations.json\"):\n",
" \"\"\"\n",
" Initialize the Firefighter Interview Assistant.\n",
" \n",
" Args:\n",
" model: ChatOpenAI model instance\n",
" conversation_storage_path: Path to the JSON file storing conversations\n",
" \"\"\"\n",
" self.storage_path = Path(conversation_storage_path)\n",
" self.current_theme: Optional[Dict] = None\n",
" self.current_resume: Optional[str] = None\n",
" self.model = model\n",
" \n",
" # Initialize storage file if it doesn't exist\n",
" if not self.storage_path.exists():\n",
" self._save_conversations({})\n",
" \n",
" # Initialize LangGraph components\n",
" self.workflow = StateGraph(state_schema=MessagesState)\n",
" self.memory = MemorySaver()\n",
" \n",
" # Set up the prompt template\n",
" self.prompt_template = ChatPromptTemplate.from_messages([\n",
" (\n",
" \"system\",\n",
" f\"\"\"\n",
" You are a Fire Fighter Interview preparation assistant.\n",
"\n",
"Throughout most Probationary Firefighter Interviews, they will be evaluating a ton of things. Typically, they want to see how you align with the **7 Main Concepts of Firefighting**. They are also watching how nervous you are, your communication skills, and your overall general competence for the role. At the end of the day, you want them to like you.\n",
"\n",
"### 7 Main Concepts:\n",
"- **High Performance Teams**\n",
"- **Situational Awareness**\n",
"- **Being a Great Problem Solver**\n",
"- **Customer Service**\n",
"- **Building Construction, Mechanical Aptitude**\n",
"- **Emergency Medicine Experience**\n",
"- **Mental and Physical Health**\n",
"\n",
"Your crew of four firefighters is usually comprised of a Driver, a Captain, and two firefighters in the back. That is a High-Performance Team. \n",
"\n",
"We are frequently dispatched to calls that require using our understanding of Building Construction Concepts, Mechanical Aptitude, and Emergency Medical Experience. When you respond to an emergency event that is inherently dangerous (like a vehicle fire, a car accident in a slanted ditch, a person trapped under a machine, a house fire, or a chemical suicide), you need to use your Situational Awareness to keep that crew safe. \n",
"\n",
"Sometimes the tools, training, and tactics that you have been taught work perfectly. Sometimes they dont. Can you be a Good Problem Solver to quickly come up with something to make the situation better for the people, places, and environments that we protect?\n",
"\n",
"Ultimately, your crew will be serving the public, and the chiefs need to know that you can be trained to be above their desired standard so that you give the public great Customer Service.\n",
"\n",
"### 20 Important Themes\n",
"Consider the 7 concepts to be the soil. All of your stories grow out of that soil. But not every story works for every question. You need to handpick the right one at the right times to give them. Sort of like how you handpick flowers out of the soil. You NEED to have **20 different flowers** so that you are fully prepared for whatever behavioral question they throw at you. These are the **20 Themes** that you would use for behavioral questions:\n",
"- Customer Service\n",
"- Conflict\n",
"- Challenge\n",
"- Leadership\n",
"- Stress\n",
"- Successful Team\n",
"- Diversity\n",
"- Mistake\n",
"- Unsuccessful Team \n",
"- Disagreement\n",
"- Bent a Rule\n",
"- Delivered a Difficult Message\n",
"- Displayed Integrity\n",
"- Took a Shortcut\n",
"- Didnt Follow the Rules\n",
"- Emergency Response\n",
"- Dealt with Disabilities\n",
"- Solved a Big Problem\n",
"- Continuous Improvement\n",
"- Handled Sensitive Information\n",
"\n",
"### Behavioral Question Starters\n",
"Behavioral questions usually start with phrases like:\n",
"- “Tell me a time when…”\n",
"- “Can you tell me about a time when you…”\n",
"- \"Describe a situation where you had to…\"\n",
"- \"Give me an example of how you…\"\n",
"- \"Have you ever been in a position where you needed to…\"\n",
"- \"Walk me through a time when you…\"\n",
"\n",
"Your goal is to engage in conversation with the user. You will be provided with the current theme, the resume of the user, and example general competency questions and behavioral questions.\n",
"\n",
"\n",
"### STARTPOP Framework\n",
"The STAR Format is what most people tell you to do in order to answer a firefighter interview question. Its a great framework. I highly recommend it. I just advise that you pump it up even further. I call it **STARTPOP**. \n",
"\n",
"Try and pull from different parts of your life. My Chief Training Officer told me that he enjoys candidates that are able to use different experiences to answer the questions. Listening to someone drone on and on about a singular time or type of event in their life is a massive turn-off to the interview panel. Thats a bad thing. Just like most things, variety is the spice of life.\n",
"\n",
"#### Components of STARTPOP:\n",
"1. **Situation**: \n",
" - Set up the answer in the mind of the question asker. \n",
" - Your storytelling skills matter here. It has to be concise and impactful (no more than 25 seconds long).\n",
" - Include dates, ages, places, and circumstances.\n",
"\n",
"2. **Task**: \n",
" - Explain what you needed to do and why you needed to do it.\n",
" - Recap the situation quickly from a different angle.\n",
"\n",
"3. **Actions**: \n",
" - Outline both the negative and the positive way of doing things.\n",
" - Show high moral character in every question.\n",
"\n",
"4. **Results**: \n",
" - Explain what happened as a result of your actions.\n",
" - Share results in a time-specific manner (e.g., “5 months later X happened”).\n",
"\n",
"5. **Transitions**: \n",
" - Speak in a way that aligns with professional expectations.\n",
" - Ensure coherence in your responses.\n",
"\n",
"6. **Personal Lessons**: \n",
" - Discuss what you learned about yourself.\n",
" - Address any concerns the interviewers might have about hiring you.\n",
"\n",
"7. **Other People Observations**: \n",
" - Share insights about others in the situation.\n",
" - Keep it short and to the point.\n",
"\n",
"8. **Professional Connection**: \n",
" - Relate your experience directly to the fire service.\n",
" - Conclude strongly, avoiding phrases like “and so yeah…”.\n",
" [Your full system prompt content]\n",
" Current theme {self.current_theme}\n",
" \n",
"\n",
"\n",
"Your task is to engage the user in conversation, ask relevant questions, that will ultimately help them prepare a strong STARTPOP response based on their experiences and the current theme.\n",
"YOU WILL BE PROVIDED WITH THE USER RESUME, ASK 1 QUESTION AT A TIME AND MAKE IT CONVERSATIONAL AND INTERESTING.\n",
"These responses will be saved and later used to generate a STARTPOP framework by US (DO NOT WORRY ABOUT THAT, WE WILL BE THE ONE TO GENERATE, JUST ENGAGE USER WITH QUESTION AND ANSWER).\n",
"Output format\n",
"\n",
"WILL BE IN JSON, avoid putting \n",
" message:\n",
" end: \"yes\" or \"no\" if you are done with asking questions and confident the responses are okay enough to prepare STARTPOP by us\n",
"\n",
"\"\"\"\n",
" \n",
" ),\n",
" MessagesPlaceholder(variable_name=\"messages\")\n",
" ])\n",
" \n",
" # Set up LangGraph workflow\n",
" self._setup_workflow()\n",
"\n",
" def _setup_workflow(self):\n",
" \"\"\"Setup LangGraph workflow\"\"\"\n",
" def call_model(state: MessagesState):\n",
" prompt = self.prompt_template.invoke(state)\n",
" response = self.model.invoke(prompt)\n",
" return {\"messages\": response}\n",
"\n",
" self.workflow.add_edge(START, \"model\")\n",
" self.workflow.add_node(\"model\", call_model)\n",
" self.app = self.workflow.compile(checkpointer=self.memory)\n",
"\n",
" def start_conversation(self, conversation_id: str, resume: str, theme: Dict) -> Dict:\n",
" \"\"\"\n",
" Start a new conversation or load an existing one.\n",
" \n",
" Args:\n",
" conversation_id: Unique identifier for the conversation\n",
" resume: User's resume content\n",
" theme: Current theme dictionary with 'theme' and 'context' keys\n",
" \n",
" Returns:\n",
" Dict containing initial AI response\n",
" \"\"\"\n",
" self.current_conversation_id = conversation_id\n",
" self.current_resume = resume\n",
" self.current_theme = theme\n",
" \n",
" # Initialize conversation in storage\n",
" conversations = self._load_conversations()\n",
" if conversation_id not in conversations:\n",
" conversations[conversation_id] = {\n",
" \"resume\": resume,\n",
" \"theme\": theme,\n",
" \"messages\": []\n",
" }\n",
" self._save_conversations(conversations)\n",
" \n",
" # Initialize conversation with resume\n",
" config = {\"configurable\": {\"thread_id\": conversation_id}}\n",
" input_messages = [HumanMessage(content=f\"Resume: {resume}\")]\n",
" output = self.app.invoke({\"messages\": input_messages}, config)\n",
" \n",
" # Parse and store initial response\n",
" response = self._parse_ai_response(output[\"messages\"][-1].content)\n",
" self.add_message(\"ai\", response[\"message\"])\n",
" \n",
" return response\n",
"\n",
" def process_user_response(self, user_message: str) -> Dict:\n",
" \"\"\"\n",
" Process user response and generate AI response.\n",
" \n",
" Args:\n",
" user_message: User's message content\n",
" \n",
" Returns:\n",
" Dict containing AI response and conversation status\n",
" \"\"\"\n",
" # Add user message to conversation\n",
" self.add_message(\"human\", user_message)\n",
" \n",
" # Prepare messages for model\n",
" messages = [HumanMessage(content=msg.content) if msg.role == \"human\" \n",
" else AIMessage(content=msg.content) \n",
" for msg in self.get_conversation_history()]\n",
" \n",
" # Generate response using LangGraph\n",
" config = {\"configurable\": {\"thread_id\": self.current_conversation_id}}\n",
" output = self.app.invoke({\"messages\": messages}, config)\n",
" \n",
" # Parse and store AI response\n",
" response = self._parse_ai_response(output[\"messages\"][-1].content)\n",
" self.add_message(\"ai\", response[\"message\"])\n",
" \n",
" return response\n",
"\n",
" def _parse_ai_response(self, content: str) -> Dict:\n",
" \"\"\"Parse AI response content into expected format\"\"\"\n",
" try:\n",
" response = json.loads(content)\n",
" return {\n",
" \"message\": response.get(\"message\", \"\"),\n",
" \"end\": response.get(\"end\", \"no\") == \"yes\"\n",
" }\n",
" except json.JSONDecodeError:\n",
" return {\n",
" \"message\": content,\n",
" \"end\": \"no\"\n",
" }\n",
"\n",
" def add_message(self, role: str, content: str) -> None:\n",
" \"\"\"[Previous implementation remains the same]\"\"\"\n",
" if not hasattr(self, 'current_conversation_id'):\n",
" raise ValueError(\"No active conversation. Call start_conversation first.\")\n",
" \n",
" from datetime import datetime\n",
" message = Message(\n",
" role=role,\n",
" content=content,\n",
" timestamp=datetime.now().isoformat()\n",
" )\n",
" \n",
" conversations = self._load_conversations()\n",
" conversations[self.current_conversation_id][\"messages\"].append({\n",
" \"role\": message.role,\n",
" \"content\": message.content,\n",
" \"timestamp\": message.timestamp\n",
" })\n",
" \n",
" self._save_conversations(conversations)\n",
"\n",
" # [Previous helper methods remain the same]\n",
" def get_conversation_history(self, conversation_id: Optional[str] = None) -> List[Message]:\n",
" \"\"\"[Previous implementation remains the same]\"\"\"\n",
" conv_id = conversation_id or self.current_conversation_id\n",
" if not conv_id:\n",
" raise ValueError(\"No conversation ID provided or active\")\n",
" \n",
" conversations = self._load_conversations()\n",
" if conv_id not in conversations:\n",
" raise ValueError(f\"Conversation {conv_id} not found\")\n",
" \n",
" return [\n",
" Message(**msg) for msg in conversations[conv_id][\"messages\"]\n",
" ]\n",
"\n",
" def _load_conversations(self) -> Dict:\n",
" \"\"\"[Previous implementation remains the same]\"\"\"\n",
" try:\n",
" with open(self.storage_path, 'r') as f:\n",
" return json.load(f)\n",
" except FileNotFoundError:\n",
" return {}\n",
"\n",
" def _save_conversations(self, conversations: Dict) -> None:\n",
" \"\"\"[Previous implementation remains the same]\"\"\"\n",
" with open(self.storage_path, 'w') as f:\n",
" json.dump(conversations, f, indent=2)\n",
"\n",
"\n",
"\n",
"\n",
"# Initialize OpenAI model\n",
"from langchain_openai import ChatOpenAI\n",
"model = ChatOpenAI(model=\"gpt-4o-mini\")\n",
"\n",
"# Initialize the assistant\n",
"assistant = FirefighterInterviewAssistant(model)\n",
"\n",
"# Start a new conversation\n",
"theme = themes[0]\n",
"response = assistant.start_conversation(\n",
" conversation_id=\"user123\",\n",
" resume=f\"Resume {docs}\",\n",
" theme=theme\n",
")\n",
"\n",
"print(response[\"message\"]) # Initial AI question\n",
"print(response[\"end\"]) # Conversation status\n",
"\n",
"# Process user response\n",
"while not response[\"end\"]:\n",
" user_input = input(\"Your response: \")\n",
" response = assistant.process_user_response(user_input)\n",
" print(response[\"message\"])"
]
},
{
"cell_type": "code",
"execution_count": 67,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"{'id': 1,\n",
" 'theme': 'Disability Questions',\n",
" 'context': \"Firefighters respond to lots of medical calls, many of which involve visible and invisible disabilities.\\n- It's critical to be aware of the unique needs of people with physical health issues and mental health challenges.\\n- Firefighters must provide compassionate care to everyone and giving respect to all regardless of their abilities.\\n- As first responders, firefighters are often the first point of contact for vulnerable individuals, and how they interact can make a lasting impact on the persons well-being.\\n- Firefighters should be well-trained to recognize different disabilities and adapt their approach to ensure effective communication and assistance, especially for those with cognitive or sensory impairments.\\n- This requires empathy, patience, and a strong understanding of mental health and physical disabilities, along with the proper use of equipment and techniques to ensure safety and dignity for everyone involved.\\n- Potential Conclusions:\\no I know that ______ Fire has a strong reputation for responding with compassion and professionalism to individuals with disabilities, ensuring that they feel respected and supported during emergencies.\\no I admire the commitment that ______ Fire has shown in ensuring firefighters are trained to work with all members of the community, including those with both visible and invisible disabilities.\\no I've seen firsthand how important it is for firefighters to provide inclusive care during medical emergencies. I would be honored to join ______ Fire in continuing to up\"}"
]
},
"execution_count": 67,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"themes[0]"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": []
},
{
"cell_type": "code",
"execution_count": 65,
"metadata": {},
"outputs": [
{
"name": "stderr",
"output_type": "stream",
"text": [
"/tmp/ipykernel_19308/4105662605.py:62: PydanticDeprecatedSince20: The `dict` method is deprecated; use `model_dump` instead. Deprecated in Pydantic V2.0 to be removed in V3.0. See Pydantic V2 Migration Guide at https://errors.pydantic.dev/2.10/migration/\n",
" \"resume\": [doc.dict() for doc in resume_docs],\n",
"/tmp/ipykernel_19308/4105662605.py:122: PydanticDeprecatedSince20: The `dict` method is deprecated; use `model_dump` instead. Deprecated in Pydantic V2.0 to be removed in V3.0. See Pydantic V2 Migration Guide at https://errors.pydantic.dev/2.10/migration/\n",
" self.conversations[conversation_id][\"messages\"].append(response.dict())\n"
]
},
{
"ename": "JSONDecodeError",
"evalue": "Expecting value: line 1 column 1 (char 0)",
"output_type": "error",
"traceback": [
"\u001b[0;31m---------------------------------------------------------------------------\u001b[0m",
"\u001b[0;31mJSONDecodeError\u001b[0m Traceback (most recent call last)",
"Cell \u001b[0;32mIn[65], line 157\u001b[0m\n\u001b[1;32m 155\u001b[0m \u001b[38;5;66;03m# Start or continue a conversation\u001b[39;00m\n\u001b[1;32m 156\u001b[0m conversation_id \u001b[38;5;241m=\u001b[39m \u001b[38;5;124m\"\u001b[39m\u001b[38;5;124muser123\u001b[39m\u001b[38;5;124m\"\u001b[39m\n\u001b[0;32m--> 157\u001b[0m response \u001b[38;5;241m=\u001b[39m \u001b[43massistant\u001b[49m\u001b[38;5;241;43m.\u001b[39;49m\u001b[43mstart_conversation\u001b[49m\u001b[43m(\u001b[49m\n\u001b[1;32m 158\u001b[0m \u001b[43m \u001b[49m\u001b[43mconversation_id\u001b[49m\u001b[38;5;241;43m=\u001b[39;49m\u001b[43mconversation_id\u001b[49m\u001b[43m,\u001b[49m\n\u001b[1;32m 159\u001b[0m \u001b[43m \u001b[49m\u001b[43mresume_docs\u001b[49m\u001b[38;5;241;43m=\u001b[39;49m\u001b[43mdocs\u001b[49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[38;5;66;43;03m# Your resume documents\u001b[39;49;00m\n\u001b[1;32m 160\u001b[0m \u001b[43m \u001b[49m\u001b[43mtheme\u001b[49m\u001b[38;5;241;43m=\u001b[39;49m\u001b[43mthemes\u001b[49m\u001b[43m[\u001b[49m\u001b[38;5;241;43m0\u001b[39;49m\u001b[43m]\u001b[49m\u001b[43m \u001b[49m\u001b[38;5;66;43;03m# Current theme\u001b[39;49;00m\n\u001b[1;32m 161\u001b[0m \u001b[43m)\u001b[49m\n\u001b[1;32m 163\u001b[0m \u001b[38;5;66;03m# Add user message and get response\u001b[39;00m\n\u001b[1;32m 164\u001b[0m response \u001b[38;5;241m=\u001b[39m assistant\u001b[38;5;241m.\u001b[39madd_message(\n\u001b[1;32m 165\u001b[0m conversation_id\u001b[38;5;241m=\u001b[39mconversation_id,\n\u001b[1;32m 166\u001b[0m message\u001b[38;5;241m=\u001b[39m\u001b[38;5;124m\"\u001b[39m\u001b[38;5;124mI have experience working in customer service.\u001b[39m\u001b[38;5;124m\"\u001b[39m,\n\u001b[1;32m 167\u001b[0m is_human\u001b[38;5;241m=\u001b[39m\u001b[38;5;28;01mTrue\u001b[39;00m\n\u001b[1;32m 168\u001b[0m )\n",
"Cell \u001b[0;32mIn[65], line 76\u001b[0m, in \u001b[0;36mFirefighterInterviewAssistant.start_conversation\u001b[0;34m(self, conversation_id, resume_docs, theme)\u001b[0m\n\u001b[1;32m 70\u001b[0m messages \u001b[38;5;241m=\u001b[39m [\n\u001b[1;32m 71\u001b[0m HumanMessage(content\u001b[38;5;241m=\u001b[39mresume_content),\n\u001b[1;32m 72\u001b[0m HumanMessage(content\u001b[38;5;241m=\u001b[39mtheme_content)\n\u001b[1;32m 73\u001b[0m ]\n\u001b[1;32m 75\u001b[0m \u001b[38;5;66;03m# Get initial response\u001b[39;00m\n\u001b[0;32m---> 76\u001b[0m response \u001b[38;5;241m=\u001b[39m \u001b[38;5;28;43mself\u001b[39;49m\u001b[38;5;241;43m.\u001b[39;49m\u001b[43m_get_response\u001b[49m\u001b[43m(\u001b[49m\u001b[43mconversation_id\u001b[49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[43mmessages\u001b[49m\u001b[43m)\u001b[49m\n\u001b[1;32m 77\u001b[0m \u001b[38;5;28;01mreturn\u001b[39;00m response\n",
"Cell \u001b[0;32mIn[65], line 125\u001b[0m, in \u001b[0;36mFirefighterInterviewAssistant._get_response\u001b[0;34m(self, conversation_id, new_messages)\u001b[0m\n\u001b[1;32m 122\u001b[0m \u001b[38;5;28mself\u001b[39m\u001b[38;5;241m.\u001b[39mconversations[conversation_id][\u001b[38;5;124m\"\u001b[39m\u001b[38;5;124mmessages\u001b[39m\u001b[38;5;124m\"\u001b[39m]\u001b[38;5;241m.\u001b[39mappend(response\u001b[38;5;241m.\u001b[39mdict())\n\u001b[1;32m 123\u001b[0m \u001b[38;5;28mself\u001b[39m\u001b[38;5;241m.\u001b[39msave_conversations()\n\u001b[0;32m--> 125\u001b[0m \u001b[38;5;28;01mreturn\u001b[39;00m \u001b[43mjson\u001b[49m\u001b[38;5;241;43m.\u001b[39;49m\u001b[43mloads\u001b[49m\u001b[43m(\u001b[49m\u001b[43mresponse\u001b[49m\u001b[38;5;241;43m.\u001b[39;49m\u001b[43mcontent\u001b[49m\u001b[43m)\u001b[49m\n",
"File \u001b[0;32m/usr/lib/python3.10/json/__init__.py:346\u001b[0m, in \u001b[0;36mloads\u001b[0;34m(s, cls, object_hook, parse_float, parse_int, parse_constant, object_pairs_hook, **kw)\u001b[0m\n\u001b[1;32m 341\u001b[0m s \u001b[38;5;241m=\u001b[39m s\u001b[38;5;241m.\u001b[39mdecode(detect_encoding(s), \u001b[38;5;124m'\u001b[39m\u001b[38;5;124msurrogatepass\u001b[39m\u001b[38;5;124m'\u001b[39m)\n\u001b[1;32m 343\u001b[0m \u001b[38;5;28;01mif\u001b[39;00m (\u001b[38;5;28mcls\u001b[39m \u001b[38;5;129;01mis\u001b[39;00m \u001b[38;5;28;01mNone\u001b[39;00m \u001b[38;5;129;01mand\u001b[39;00m object_hook \u001b[38;5;129;01mis\u001b[39;00m \u001b[38;5;28;01mNone\u001b[39;00m \u001b[38;5;129;01mand\u001b[39;00m\n\u001b[1;32m 344\u001b[0m parse_int \u001b[38;5;129;01mis\u001b[39;00m \u001b[38;5;28;01mNone\u001b[39;00m \u001b[38;5;129;01mand\u001b[39;00m parse_float \u001b[38;5;129;01mis\u001b[39;00m \u001b[38;5;28;01mNone\u001b[39;00m \u001b[38;5;129;01mand\u001b[39;00m\n\u001b[1;32m 345\u001b[0m parse_constant \u001b[38;5;129;01mis\u001b[39;00m \u001b[38;5;28;01mNone\u001b[39;00m \u001b[38;5;129;01mand\u001b[39;00m object_pairs_hook \u001b[38;5;129;01mis\u001b[39;00m \u001b[38;5;28;01mNone\u001b[39;00m \u001b[38;5;129;01mand\u001b[39;00m \u001b[38;5;129;01mnot\u001b[39;00m kw):\n\u001b[0;32m--> 346\u001b[0m \u001b[38;5;28;01mreturn\u001b[39;00m \u001b[43m_default_decoder\u001b[49m\u001b[38;5;241;43m.\u001b[39;49m\u001b[43mdecode\u001b[49m\u001b[43m(\u001b[49m\u001b[43ms\u001b[49m\u001b[43m)\u001b[49m\n\u001b[1;32m 347\u001b[0m \u001b[38;5;28;01mif\u001b[39;00m \u001b[38;5;28mcls\u001b[39m \u001b[38;5;129;01mis\u001b[39;00m \u001b[38;5;28;01mNone\u001b[39;00m:\n\u001b[1;32m 348\u001b[0m \u001b[38;5;28mcls\u001b[39m \u001b[38;5;241m=\u001b[39m JSONDecoder\n",
"File \u001b[0;32m/usr/lib/python3.10/json/decoder.py:337\u001b[0m, in \u001b[0;36mJSONDecoder.decode\u001b[0;34m(self, s, _w)\u001b[0m\n\u001b[1;32m 332\u001b[0m \u001b[38;5;28;01mdef\u001b[39;00m\u001b[38;5;250m \u001b[39m\u001b[38;5;21mdecode\u001b[39m(\u001b[38;5;28mself\u001b[39m, s, _w\u001b[38;5;241m=\u001b[39mWHITESPACE\u001b[38;5;241m.\u001b[39mmatch):\n\u001b[1;32m 333\u001b[0m \u001b[38;5;250m \u001b[39m\u001b[38;5;124;03m\"\"\"Return the Python representation of ``s`` (a ``str`` instance\u001b[39;00m\n\u001b[1;32m 334\u001b[0m \u001b[38;5;124;03m containing a JSON document).\u001b[39;00m\n\u001b[1;32m 335\u001b[0m \n\u001b[1;32m 336\u001b[0m \u001b[38;5;124;03m \"\"\"\u001b[39;00m\n\u001b[0;32m--> 337\u001b[0m obj, end \u001b[38;5;241m=\u001b[39m \u001b[38;5;28;43mself\u001b[39;49m\u001b[38;5;241;43m.\u001b[39;49m\u001b[43mraw_decode\u001b[49m\u001b[43m(\u001b[49m\u001b[43ms\u001b[49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[43midx\u001b[49m\u001b[38;5;241;43m=\u001b[39;49m\u001b[43m_w\u001b[49m\u001b[43m(\u001b[49m\u001b[43ms\u001b[49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[38;5;241;43m0\u001b[39;49m\u001b[43m)\u001b[49m\u001b[38;5;241;43m.\u001b[39;49m\u001b[43mend\u001b[49m\u001b[43m(\u001b[49m\u001b[43m)\u001b[49m\u001b[43m)\u001b[49m\n\u001b[1;32m 338\u001b[0m end \u001b[38;5;241m=\u001b[39m _w(s, end)\u001b[38;5;241m.\u001b[39mend()\n\u001b[1;32m 339\u001b[0m \u001b[38;5;28;01mif\u001b[39;00m end \u001b[38;5;241m!=\u001b[39m \u001b[38;5;28mlen\u001b[39m(s):\n",
"File \u001b[0;32m/usr/lib/python3.10/json/decoder.py:355\u001b[0m, in \u001b[0;36mJSONDecoder.raw_decode\u001b[0;34m(self, s, idx)\u001b[0m\n\u001b[1;32m 353\u001b[0m obj, end \u001b[38;5;241m=\u001b[39m \u001b[38;5;28mself\u001b[39m\u001b[38;5;241m.\u001b[39mscan_once(s, idx)\n\u001b[1;32m 354\u001b[0m \u001b[38;5;28;01mexcept\u001b[39;00m \u001b[38;5;167;01mStopIteration\u001b[39;00m \u001b[38;5;28;01mas\u001b[39;00m err:\n\u001b[0;32m--> 355\u001b[0m \u001b[38;5;28;01mraise\u001b[39;00m JSONDecodeError(\u001b[38;5;124m\"\u001b[39m\u001b[38;5;124mExpecting value\u001b[39m\u001b[38;5;124m\"\u001b[39m, s, err\u001b[38;5;241m.\u001b[39mvalue) \u001b[38;5;28;01mfrom\u001b[39;00m\u001b[38;5;250m \u001b[39m\u001b[38;5;28;01mNone\u001b[39;00m\n\u001b[1;32m 356\u001b[0m \u001b[38;5;28;01mreturn\u001b[39;00m obj, end\n",
"\u001b[0;31mJSONDecodeError\u001b[0m: Expecting value: line 1 column 1 (char 0)"
]
}
],
"source": [
"from typing import List, Dict, Optional\n",
"from langchain_core.messages import HumanMessage, AIMessage, SystemMessage\n",
"from langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholder\n",
"from langchain_openai import ChatOpenAI\n",
"from langchain.schema import Document\n",
"import json\n",
"import os\n",
"\n",
"class FirefighterInterviewAssistant:\n",
" def __init__(self, model_name: str = \"gpt-4-turbo-preview\"):\n",
" \"\"\"Initialize the interview assistant.\n",
" \n",
" Args:\n",
" model_name (str): The OpenAI model to use\n",
" \"\"\"\n",
" self.model = ChatOpenAI(model_name=model_name)\n",
" self.conversations_file = \"conversations.json\"\n",
" self.load_conversations()\n",
" \n",
" # Core system prompt template\n",
" self.prompt_template = ChatPromptTemplate.from_messages([\n",
" (\n",
" \"system\",\n",
" \"\"\"You are a Fire Fighter Interview preparation assistant.\n",
" // ... existing system prompt content ...\n",
" Output format:\n",
" WILL BE IN JSON\n",
" message:\n",
" end: \"yes\" or \"no\" if you are done with asking questions and confident the responses are okay enough to prepare STARTPOP\n",
" \"\"\"\n",
" ),\n",
" MessagesPlaceholder(variable_name=\"messages\")\n",
" ])\n",
"\n",
" def load_conversations(self):\n",
" \"\"\"Load existing conversations from JSON file\"\"\"\n",
" if os.path.exists(self.conversations_file):\n",
" with open(self.conversations_file, 'r') as f:\n",
" self.conversations = json.load(f)\n",
" else:\n",
" self.conversations = {}\n",
"\n",
" def save_conversations(self):\n",
" \"\"\"Save conversations to JSON file\"\"\"\n",
" with open(self.conversations_file, 'w') as f:\n",
" json.dump(self.conversations, f, indent=2)\n",
"\n",
" def start_conversation(self, conversation_id: str, resume_docs: List[Document], theme: Dict) -> Dict:\n",
" \"\"\"Start a new conversation or continue existing one.\n",
" \n",
" Args:\n",
" conversation_id (str): Unique identifier for the conversation\n",
" resume_docs (List[Document]): List of resume documents\n",
" theme (Dict): Current theme information\n",
" \n",
" Returns:\n",
" Dict: Initial response from the assistant\n",
" \"\"\"\n",
" if conversation_id not in self.conversations:\n",
" self.conversations[conversation_id] = {\n",
" \"messages\": [],\n",
" \"resume\": [doc.dict() for doc in resume_docs],\n",
" \"theme\": theme\n",
" }\n",
" \n",
" # Initialize with resume and theme context\n",
" resume_content = f\"Resume {str(resume_docs)}\"\n",
" theme_content = f\"Current theme: {theme['theme']}\\nContext: {theme['context']}\"\n",
" \n",
" messages = [\n",
" HumanMessage(content=resume_content),\n",
" HumanMessage(content=theme_content)\n",
" ]\n",
" \n",
" # Get initial response\n",
" response = self._get_response(conversation_id, messages)\n",
" return response\n",
"\n",
" def add_message(self, conversation_id: str, message: str, is_human: bool = True) -> Dict:\n",
" \"\"\"Add a message to the conversation and get response.\n",
" \n",
" Args:\n",
" conversation_id (str): Conversation identifier\n",
" message (str): Message content\n",
" is_human (bool): Whether the message is from human (True) or AI (False)\n",
" \n",
" Returns:\n",
" Dict: Response from the assistant\n",
" \"\"\"\n",
" if conversation_id not in self.conversations:\n",
" raise ValueError(f\"Conversation {conversation_id} not found\")\n",
" \n",
" message_obj = HumanMessage(content=message) if is_human else AIMessage(content=message)\n",
" self.conversations[conversation_id][\"messages\"].append(message_obj.dict())\n",
" \n",
" # Get response if human message\n",
" if is_human:\n",
" return self._get_response(conversation_id, [message_obj])\n",
" return {\"message\": \"Message added\", \"end\": \"no\"}\n",
"\n",
"\n",
"\n",
" def _get_response(self, conversation_id: str, new_messages: List) -> Dict:\n",
" \"\"\"Get response from the model.\n",
" \n",
" Args:\n",
" conversation_id (str): Conversation identifier\n",
" new_messages (List): New messages to process\n",
" \n",
" Returns:\n",
" Dict: Response from the assistant\n",
" \"\"\"\n",
" # Combine existing and new messages\n",
" all_messages = [\n",
" self._convert_to_message(msg) \n",
" for msg in self.conversations[conversation_id][\"messages\"]\n",
" ] + new_messages\n",
" \n",
" # Get response from model\n",
" prompt = self.prompt_template.invoke({\"messages\": all_messages})\n",
" response = self.model.invoke(prompt)\n",
" \n",
" # Save response\n",
" self.conversations[conversation_id][\"messages\"].append(response.dict())\n",
" self.save_conversations()\n",
" \n",
" return json.loads(response.content)\n",
"\n",
" def _convert_to_message(self, message_dict: Dict):\n",
" \"\"\"Convert dictionary to appropriate message type\"\"\"\n",
" if message_dict[\"type\"] == \"human\":\n",
" return HumanMessage(**message_dict)\n",
" elif message_dict[\"type\"] == \"ai\":\n",
" return AIMessage(**message_dict)\n",
" elif message_dict[\"type\"] == \"system\":\n",
" return SystemMessage(**message_dict)\n",
" else:\n",
" raise ValueError(f\"Unknown message type: {message_dict['type']}\")\n",
"\n",
" def get_conversation_history(self, conversation_id: str) -> List[Dict]:\n",
" \"\"\"Get the full conversation history.\n",
" \n",
" Args:\n",
" conversation_id (str): Conversation identifier\n",
" \n",
" Returns:\n",
" List[Dict]: List of messages in the conversation\n",
" \"\"\"\n",
" if conversation_id not in self.conversations:\n",
" raise ValueError(f\"Conversation {conversation_id} not found\")\n",
" return self.conversations[conversation_id][\"messages\"]\n",
"\n",
"\n",
"# Initialize the assistant\n",
"assistant = FirefighterInterviewAssistant()\n",
"\n",
"# Start or continue a conversation\n",
"conversation_id = \"user123\"\n",
"response = assistant.start_conversation(\n",
" conversation_id=conversation_id,\n",
" resume_docs=docs, # Your resume documents\n",
" theme=themes[0] # Current theme\n",
")\n",
"\n",
"# Add user message and get response\n",
"response = assistant.add_message(\n",
" conversation_id=conversation_id,\n",
" message=\"I have experience working in customer service.\",\n",
" is_human=True\n",
")\n",
"\n",
"# Get conversation history\n",
"history = assistant.get_conversation_history(conversation_id)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": []
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": []
},
{
"cell_type": "code",
"execution_count": 48,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"{'messages': [HumanMessage(content=\"Resume [Document(metadata={'source': '../upload_folder/Resume_-_Erika_Kiviaho.pdf', 'page': 0}, page_content='Erika Kiviaho \\\\n \\\\n \\\\n1070 Hallets Road, MacTier, ON, P0C 1H0 \\\\nEkiviaho_9@hotmail.com \\\\n(705) 662 9735\\\\nEDUCATION \\\\nCollege Certificate, NFPA 1001 Level 1 & 2 Pre-Service Firefighter Program, FESTI (IFSAC) 2023 \\\\nUniversity Degree, General Bachelor of Arts, Wilfrid Laurier University 2016 \\\\nOntario Secondary School Diploma (OSSD), Lively District Secondary School, Sudbury, ON 2010 \\\\n \\\\nFIREFIGHTER EDUCATION AND CERTIFICATIONS \\\\nOFAI Stage 1, 2, 3 and Swim Test Candidate Testing Program Certificate 2023 \\\\nNFPA 1001 Level 1 & 2 Pre-Service Firefighter Training Program, FESTI (IFSAC) 2023 \\\\nNFPA 1006 Surface Water Rescue Technician Level, Southwest Fire Academy 2023 \\\\nNFPA 1006 Common Passenger Vehicle Rescue Technician Level, RS Rescue 2024 \\\\nNFPA 1006 Confined Space Rescue Technician Level, Access Rescue 2024 \\\\nNFPA 1035 Fire & Life Safety Educator, Conestoga College (IFSAC) 2024 \\\\nNFPA 1072 Hazardous Materials - Awareness & Operations Level, Lambton College (IFSAC) 2023 \\\\nSuppression Tactics in Single Family Homes, UL Fire Safety Research Institute 2023 \\\\n \\\\nFIRST AID AND LIFE SAFETY TRAINING \\\\nEmergency Medical Responder + CPR Level BLS (HCP), Canadian Red Cross 2023 \\\\nStandard First Aid, BLS and CPR Level C, Canadian Red Cross 2023 \\\\nPsychological First Aid, John Hopkins University 2023 \\\\n \\\\nEMERGENCY MANAGEMENT ONTARIO EDUCATION \\\\nIMS 100 Intro to Incident Management System, EMO 2023 \\\\n \\\\nEMERGENCY RESPONSE PREPARATION AND SAFETY TRAINING \\\\nOntario DZ License (with airbrakes) Training, Transport Training Centres of Canada 2023 \\\\nPleasure Craft Operator License, Transport Canada 2023 \\\\nWHIMS 2015, Workplace Safety Compliance Centre 2023 \\\\nWorking at Heights, Workplace Safety Compliance Centre 2023 \\\\nAsbestos Safety Awareness, Workplace Safety Compliance Centre 2023 \\\\n \\\\nEQUITY, DIVERSITY, INCLUSION AND LANGUAGE TRAINING \\\\nAmerican Sign Language for First Responders, Humber College 2023 \\\\nAccessibility for Ontarians with Disabilities, AODA.ca 2023 \\\\nLGBT2SQ+ Inclusion Training, Canadian Police Knowledge Network 2023 \\\\n \\\\nWORK EXPERIENCE \\\\nVolunteer Firefighter Muskoka Lakes Fire Department, Foots Bay, ON 2023 Present \\\\n• Member of Muskoka Lakes Volunteer Fire Suppression Team training out of and responding from Station 1. \\\\n• Works closely with firefighting crew under the guidance and direction of our Captain and Chiefs to respond to \\\\na variety of emergency situations (such as medical emergencies, car accidents and fully involved house fires). \\\\n• Maintains excellent rate of attendance for active calls, training days and community volunteering events. \\\\n• Responsible for operating, maintaining, servicing equipment, and performing physically demanding labour. \\\\n• Performs daily inspections, truck and apparatus circle checks, documents and restocks inventory. \\\\n• Frequently interacts with the public presenting fire safety messages and providing emotional support . \\\\n• Required to constantly use problem solving, stress management, communication , and team working skills. \\\\n• Complies with the Fire Protection and Prevention Act of Ontario and Section 21 Guidelines. \\\\n• Ensures compliance with the Occupational Health and Safety Act Section 28 Duties of Workers. \\\\n \\\\nLabourer Sundance Gardening, Muskoka, ON 2023 Present \\\\n• Worked on a crew of landscaping professionals servicing residential cottage clients across the Muskokas. \\\\n• Responsible for building rock beds, building flower beds, cutting grass, planting trees and watering plants. \\\\n• Frequently drove, loaded, and unloaded large pick-up trucks, cube vans,
" AIMessage(content=\"Hi Erika! It's great to meet you, and thank you for sharing your resume. You have a solid background with various experiences that can really lend themselves well to the firefighter interview.\\n\\nLet's start by focusing on the **20 Themes**. Which theme would you like to discuss today? For example, we could explore themes like **Customer Service**, **Conflict**, **Challenge**, or any one of the others. This will help us hone in on specific experiences you've encountered that align with the **7 Main Concepts of Firefighting**.\", additional_kwargs={'refusal': None}, response_metadata={'token_usage': {'completion_tokens': 107, 'prompt_tokens': 3225, 'total_tokens': 3332, 'completion_tokens_details': {'accepted_prediction_tokens': 0, 'audio_tokens': 0, 'reasoning_tokens': 0, 'rejected_prediction_tokens': 0}, 'prompt_tokens_details': {'audio_tokens': 0, 'cached_tokens': 0}}, 'model_name': 'gpt-4o-mini-2024-07-18', 'system_fingerprint': 'fp_72ed7ab54c', 'finish_reason': 'stop', 'logprobs': None}, id='run-5421de84-9594-45d4-96af-5e0495287f6a-0', usage_metadata={'input_tokens': 3225, 'output_tokens': 107, 'total_tokens': 3332, 'input_token_details': {'audio': 0, 'cache_read': 0}, 'output_token_details': {'audio': 0, 'reasoning': 0}}),\n",
" HumanMessage(content='customer service', additional_kwargs={}, response_metadata={}, id='90f3dd69-6420-4f6d-bc26-b95b4828eea0'),\n",
" AIMessage(content=\"Great choice, Erika! Customer service is a crucial aspect of firefighting, as you'll be interacting with the public during high-stress situations. Let's delve into that theme.\\n\\nTo construct a strong **STARTPOP** response around customer service, I have a few questions for you:\\n\\n1. Can you recall a specific situation where you provided exceptional customer service in a high-pressure environment? What was happening at the time?\\n \\n2. What actions did you take that demonstrated your commitment to excellent service? \\n\\n3. What was the outcome of your actions, both for the customer and for yourself? \\n\\n4. Did you learn any important lessons from that experience that you could apply to your role as a firefighter? \\n\\n5. Can you share any observations about how your team or others responded to your customer service in that situation?\\n\\nFeel free to provide details from your past experiences, and we'll work together to shape them into a strong response!\", additional_kwargs={'refusal': None}, response_metadata={'token_usage': {'completion_tokens': 186, 'prompt_tokens': 3341, 'total_tokens': 3527, 'completion_tokens_details': {'accepted_prediction_tokens': 0, 'audio_tokens': 0, 'reasoning_tokens': 0, 'rejected_prediction_tokens': 0}, 'prompt_tokens_details': {'audio_tokens': 0, 'cached_tokens': 0}}, 'model_name': 'gpt-4o-mini-2024-07-18', 'system_fingerprint': 'fp_72ed7ab54c', 'finish_reason': 'stop', 'logprobs': None}, id='run-9a0161a1-aaf4-49cc-a379-385419da3108-0', usage_metadata={'input_tokens': 3341, 'output_tokens': 186, 'total_tokens': 3527, 'input_token_details': {'audio': 0, 'cache_read': 0}, 'output_token_details': {'audio': 0, 'reasoning': 0}})]}"
]
},
"execution_count": 48,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"output"
]
},
{
"cell_type": "code",
"execution_count": 47,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"==================================\u001b[1m Ai Message \u001b[0m==================================\n",
"\n",
"Great choice, Erika! Customer service is a crucial aspect of firefighting, as you'll be interacting with the public during high-stress situations. Let's delve into that theme.\n",
"\n",
"To construct a strong **STARTPOP** response around customer service, I have a few questions for you:\n",
"\n",
"1. Can you recall a specific situation where you provided exceptional customer service in a high-pressure environment? What was happening at the time?\n",
" \n",
"2. What actions did you take that demonstrated your commitment to excellent service? \n",
"\n",
"3. What was the outcome of your actions, both for the customer and for yourself? \n",
"\n",
"4. Did you learn any important lessons from that experience that you could apply to your role as a firefighter? \n",
"\n",
"5. Can you share any observations about how your team or others responded to your customer service in that situation?\n",
"\n",
"Feel free to provide details from your past experiences, and we'll work together to shape them into a strong response!\n"
]
}
],
"source": [
"config = {\"configurable\": {\"thread_id\": \"abc345\"}}\n",
"query = f\"customer service\"\n",
"\n",
"input_messages = [HumanMessage(query)]\n",
"output = app.invoke({\"messages\": input_messages}, config)\n",
"output[\"messages\"][-1].pretty_print()"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": []
},
{
"cell_type": "code",
"execution_count": 43,
"metadata": {},
"outputs": [],
"source": [
"from langgraph.checkpoint.memory import MemorySaver\n",
"from langgraph.graph import START, MessagesState, StateGraph\n",
"workflow = StateGraph(state_schema=MessagesState)\n",
"\n",
"def call_model(state: MessagesState):\n",
" prompt = prompt_template.invoke(state)\n",
" response = model.invoke(prompt)\n",
" return {\"messages\": response}\n",
"\n",
"\n",
"workflow.add_edge(START, \"model\")\n",
"workflow.add_node(\"model\", call_model)\n",
"\n",
"memory = MemorySaver()\n",
"app = workflow.compile(checkpointer=memory)"
]
},
{
"cell_type": "code",
"execution_count": 44,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"==================================\u001b[1m Ai Message \u001b[0m==================================\n",
"\n",
"Hi Jim! How can I assist you today?\n"
]
}
],
"source": [
"config = {\"configurable\": {\"thread_id\": \"abc345\"}}\n",
"query = \"Hi! I'm Jim.\"\n",
"\n",
"input_messages = [HumanMessage(query)]\n",
"output = app.invoke({\"messages\": input_messages}, config)\n",
"output[\"messages\"][-1].pretty_print()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"prompt_template = ChatPromptTemplate.from_messages(\n",
" [\n",
" (\n",
" \"system\",\n",
" \"You are a helpful assistant. Answer all questions to the best of your ability in {language}.\",\n",
" ),\n",
" MessagesPlaceholder(variable_name=\"messages\"),\n",
" ]\n",
")"
]
},
{
"cell_type": "code",
"execution_count": 45,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"==================================\u001b[1m Ai Message \u001b[0m==================================\n",
"\n",
"Your name is Jim. How can I help you today, Jim?\n"
]
}
],
"source": [
"query = \"What is my name?\"\n",
"\n",
"input_messages = [HumanMessage(query)]\n",
"output = app.invoke({\"messages\": input_messages}, config)\n",
"output[\"messages\"][-1].pretty_print()"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": []
}
],
"metadata": {
"kernelspec": {
"display_name": "venv",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.10.13"
}
},
"nbformat": 4,
"nbformat_minor": 2
}