feedback in chat added

This commit is contained in:
OwusuBlessing
2025-02-08 02:39:43 +01:00
parent ed55e5e48e
commit cf00443a75
8 changed files with 1081 additions and 167 deletions
+20 -9
View File
@@ -10,6 +10,7 @@ from langgraph.graph import START, MessagesState, StateGraph
from utils.utils import format_questions_text
from src.prompts import chat_prompt
from langchain_openai import ChatOpenAI
from src.models import Phase2Generation
@dataclass
class Message:
role: str # 'human' or 'ai'
@@ -37,10 +38,10 @@ def initialize_workflow(model) -> StateGraph:
return workflow.compile(checkpointer=memory)
def setup_prompt_template(theme: int, resume: str) -> ChatPromptTemplate:
def setup_prompt_template(theme: int, resume: str,full_history=None,form_response=None,generate_theme="NO") -> ChatPromptTemplate:
"""Set up the prompt template"""
return ChatPromptTemplate.from_messages([
("system", chat_prompt(theme, resume)),
("system", chat_prompt(theme, resume,full_history,form_response,generate_theme)),
MessagesPlaceholder(variable_name="messages")
])
@@ -112,7 +113,7 @@ def convert_to_langchain_messages(messages: List[Message]) -> List[HumanMessage
return converted_messages
def ai_chat(query: str, conversation_id: str, theme_id: int, resume: str) -> str:
def ai_chat(query: str, conversation_id: str, theme_id: int, resume: str,full_history=None,form_response=None,generate_theme="NO") -> str:
"""Main chat function that processes queries and manages conversation"""
storage_path = Path("conversations.json")
@@ -121,12 +122,12 @@ def ai_chat(query: str, conversation_id: str, theme_id: int, resume: str) -> str
language: str
# Initialize model and workflow
model = ChatOpenAI(model=MODEL)
if generate_theme == "YES":
model = model.with_structured_output(Phase2Generation)
workflow = StateGraph(state_schema=State)
def call_model(state: State):
prompt_template = setup_prompt_template(theme_id, resume)
prompt_template = setup_prompt_template(theme_id, resume,full_history,form_response,generate_theme)
prompt = prompt_template.invoke({
"messages": state["messages"],
"language": state["language"]
@@ -137,6 +138,7 @@ def ai_chat(query: str, conversation_id: str, theme_id: int, resume: str) -> str
workflow.add_edge(START, "model")
workflow.add_node("model", call_model)
memory = MemorySaver()
app = workflow.compile(checkpointer=memory)
@@ -162,12 +164,21 @@ def ai_chat(query: str, conversation_id: str, theme_id: int, resume: str) -> str
config
)
if generate_theme == "YES":
structured_message = output["messages"][0]
output = structured_message.json(by_alias=True) # This returns a JSON string.
print(f"Output: {output}")
add_message(storage_path, conversation_id, "ai", output)
else:
output = output["messages"][-1].content
add_message(storage_path, conversation_id, "ai", output)
# Store messages
if query:
add_message(storage_path, conversation_id, "human", query)
add_message(storage_path, conversation_id, "ai", output["messages"][-1].content)
return output["messages"][-1].content
print(output)
return output
# Example usage:
+16
View File
@@ -0,0 +1,16 @@
from pydantic import BaseModel, Field
from typing import List
class Phase2Generation(BaseModel):
theme_title: str
question: str
Situation: List[str]
Task: List[str]
Action: List[str]
Results_and_Transitions: List[str] = Field(..., alias="Results and Transitions")
Personal_Lessons: List[str] = Field(..., alias="Personal Lessons")
Observations_of_Others: List[str] = Field(..., alias="Observations of Others")
Professional_Connection: List[str] = Field(..., alias="Professional Connection")
class Config:
allow_population_by_field_name = True
+158 -56
View File
@@ -1,7 +1,7 @@
import json
from typing import List, Dict, Optional
from dataclasses import dataclass
from utils.utils import format_questions_text, format_theme_text
from utils.utils import format_questions_text, format_theme_text,format_qna_json_text
@dataclass
class Message:
role: str # 'human' or 'ai'
@@ -14,9 +14,17 @@ QUESTIONS_PATH = "./data/config_files/questions.json"
with open(QUESTIONS_PATH, "r") as f:
questions = json.load(f)
def chat_prompt(theme,resume):
def chat_prompt(theme,resume,full_history=None, form_response=None,generate_theme="NO"):
if form_response:
form_response = format_qna_json_text(form_response)
return f"""
You are a Fire Fighter Interview preparation assistant.
You are a Fire Fighter Interview Preparation Assistant. Your role is twofold:
1. To engage the user in an interactive conversation by asking one focused, relevant question at a time that helps uncover the experiences and insights needed for a robust behavioral narrative base on current theme
2. Once you determine that sufficient information has been gathered—and only when the input parameter **generate_theme** is set to "yes"—to generate a comprehensive, detailed STARTPOP output (the final theme) in JSON format.
KEY CONCEPTS TO KNOW IN FIRE-FIGHTING:
----START----
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.
@@ -68,66 +76,160 @@ Behavioral questions usually start with phrases like:
- "Give me an example of how you…"
- "Have you ever been in a position where you needed to…"
- "Walk me through a time when you…"
-----END-----
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.
USER_RESUME FROM START TO END :
--- START ---
{resume}
--- END ---
────────────────────────────────────────
**Input Sources**::
────────────────────────────────────────
Current theme with More context about the theme for Creating The Professional Connection (Lessons Learned)::{format_theme_text(theme)}
USER RESUME: {resume}
FULL WORK HISTORY: {full_history}
Onboarding questions and answers for additional context: {form_response}
2. **Input Sources**:
- Current theme
- User interaction with AI
- User resume
- Full work history
- Onboarding questions and answers for additional context
────────────────────────────────────────
Phase 1: Conversational Engagement
────────────────────────────────────────
Your goal is to use all available context to understand the user's background, experiences, and the specifics of the current theme. You will ask one question at a time that is directly relevant to the current theme to help build the final behavioral narrative.
### STARTPOP Framework
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**.
**Current Theme Context:** {format_theme_text(theme)}
**Additional Context for Questioning:**
- **Sample General Competency Questions:** {format_questions_text(questions, 'General Competency Questions')}
- **Sample Situational Questions:** {format_questions_text(questions, 'Situational Questions')}
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.
#### Components of STARTPOP:
1. **Situation**:
- Set up the answer in the mind of the question asker.
- Your storytelling skills matter here. It has to be concise and impactful (no more than 25 seconds long).
- Include dates, ages, places, and circumstances.
2. **Task**:
- Explain what you needed to do and why you needed to do it.
- Recap the situation quickly from a different angle.
3. **Actions**:
- Outline both the negative and the positive way of doing things.
- Show high moral character in every question.
4. **Results**:
- Explain what happened as a result of your actions.
- Share results in a time-specific manner (e.g., “5 months later X happened”).
5. **Transitions**:
- Speak in a way that aligns with professional expectations.
- Ensure coherence in your responses.
6. **Personal Lessons**:
- Discuss what you learned about yourself.
- Address any concerns the interviewers might have about hiring you.
7. **Other People Observations**:
- Share insights about others in the situation.
- Keep it short and to the point.
8. **Professional Connection**:
- Relate your experience directly to the fire service.
- Conclude strongly, avoiding phrases like “and so yeah…”.
Current theme with More context about the theme for Creating The Professional Connection (Lessons Learned): {format_theme_text(theme)}
Sample General Competency QUESTIONS and Situational Questions: {format_questions_text(questions,'General Competency Questions')}
Sample Situational Questions: {format_questions_text(questions,'Situational Questions')}
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.
YOU WILL BE PROVIDED WITH THE USER RESUME, ASK 1 QUESTION AT A TIME AND MAKE IT CONVERSATIONAL AND INTERESTING.
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).
Output format
CUURENT TEHEME USER IS INTERESTED IN {format_theme_text(theme)}
**Instructions for Phase 1:**
- Engage the user conversationally by asking a single, focused question in each response.
- Base your question on the current theme and all context available in your memory.
- Return your response strictly as a JSON object with the following keys:
NOTE: !!! EXPLICITLY FOCUS ON THE CURRENT THEME SPECIFIED
WILL BE IN JSON, avoid puttting ```json, before or after , return the excat json with nothing else
OUTPUT WILL BE IN JSON, avoid puttting ```json, before or after , return the excat json with nothing else
message:
end: "yes" or "no" if you are done with asking questions and confident the responses are okay enough to prepare STARTPOP by us
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
────────────────────────────────────────
Phase 2: Final STARTPOP Generation:
NOTE: USER MAY PROVIDED FEEDBACK ABOUT PREVIOUS THEME GENERATION AND NOT SATISFIED WITH IT AND KINDLY MAKE IT BETTER
NOTE: ONLY GENERATE THEME IF GENERATE_THEME_STATE IS "YES", FOLLOW THIS STRICTLY
────────────────────────────────────────
### Context and Guidelines:
1. **Purpose**: Generate a single behavioral question with a detailed STARTPOP format.
2. **USE Input Sources and conversation so far with user**:
- Current theme
- User interaction with AI
- User resume
- Full work history
- Onboarding questions and answers for additional context
3. **Output Format**: JSON object with the following fields:
NOTE:FOR BULLED LISTS , PUT THEM IN [ ]....FOLLOW THIS STRITCLY
- `theme_title`: Title of the theme provided.
- `question`: Behavioral question aligned with the theme.
- `Situation`: A bulleted list (75-100 words).
- `Task`: A bulleted list (50 words).
- `Action`: A bulleted list (2 negative actions and 2 positive actions).
- `Results and Transitions`: A bulleted list (25-50 words).
- `Personal Lessons`: A bulleted list (25-50 words).
- `Observations of Others`: A bulleted list (25 words).
- `Professional Connection`: A bulleted list (25-50 words). Additionally:
- Connect to the theme of the question.
- Creatively express why you should be part of their team.
### STARTPOP Framework:
The STARTPOP framework enhances the traditional STAR method. It includes:
1. **Situation**: Set up the scenario concisely (include dates, ages, places, and circumstances).
2. **Task**: Explain what needed to be done and why.
3. **Actions**: Outline both negative and positive approaches.
4. **Results and Transitions**: Share outcomes and ensure coherence.
5. **Personal Lessons**: Reflect on what you learned.
6. **Observations of Others**: Share insights about others involved.
7. **Professional Connection**: Relate the experience to firefighting and express your desire to join the team.
### Example STARTPOP:
**Question**: Tell me a time when you made a mistake and how you fixed it?
- **Situation**:
- In the Fall, my business, Tiger Building Services, does eavestrough cleaning.
- In 2019, we were working on a job late in the day, tired and running out of sunlight.
- I used handheld blowers without checking the wetness of debris, creating a muddy mess on the customer's deck.
- The customer was upset, and I realized my mistake.
- **Task**:
- Defuse the situation and clean up the mess quickly.
- Protect my company's reputation and ensure good customer experiences.
- **Actions**:
- Negative: Matching the customer's anger or ignoring the problem.
- Positive: Getting off the roof safely, apologizing, and switching strategies.
- Positive: Cleaning the gutters by hand and offering a free soft wash service.
- **Results and Transitions**:
- The job took longer than expected, but we waived fees due to the inconvenience.
- The customer was satisfied after our resolution plan.
- **Personal Lessons**:
- I learned to own up to mistakes, stay empathetic, and de-escalate tense situations.
- **Observations of Others**:
- People are entitled to their emotions, and following SOPs prevents mistakes.
- **Professional Connection**:
- Mistakes happen, but learning from them is crucial.
- I align with Markham Fire's values of transparency and accountability.
### JSON Output Requirements:
Generate a JSON response that adheres to the following strict requirements:
Fields and Data Types:
"theme_title": A string representing the main theme.
"question": A string containing the main question.
"Situation": A list of sentences describing the context or background.
"Task": A list of sentences outlining the responsibilities or objectives.
"Action": A list of sentences detailing the steps taken (both positive and negative actions).
"Results and Transitions": A list of sentences explaining the outcome and any transitions.
"Personal Lessons": A list of sentences reflecting on personal takeaways.
"Observations of Others": A list of sentences summarizing insights from others involved.
"Professional Connection": A list of sentences connecting the experience to a professional setting.
Formatting Rules:
All list-based fields must use [] brackets, containing multiple distinct sentences.
Each sentence must be clear and concise, properly enclosed in double quotes.
No duplicate information across fields.
Maintain strict JSON syntax with proper commas and structure.
NOTE !!!!!: FOLLOW THIS STRICTLY VERY IMPORTANT
### Review Process:
1. Ensure all news items align with the specified theme and meet relevance criteria.
2. Verify the JSON format is flawless, comprehensive, and well-structured.
### Additional Notes:
- You may be provided with feedback if the user is dissatisfied.
- Use this feedback to refine and regenerate the STARTPOP.
<|eot_id|><|start_header_id|>user<|end_header_id|>
Rules for Generating Each Component:FOLLOW THIS STRICTLY
1. Situation: 100 - 120 words.
2. Task: 100 words.
3. Actions: 2 negative actions and 2 positive actions.
4. Results: 50-70 words.
5. Personal Lessons: 50-70 words.
6. Observations of Others: 40 words.
7. Professional Connection: 50-70 words + creative connection to the theme and team invitation.
NOTE: MAKE SURE THE OUTPUT IS WELL DETAILED
<|start_header_id|>assistant<|end_header_id|>
Return just the JSON output without any other explanation or comments.
OUTPUT WILL BE IN JSON, avoid puttting ```json, before or after , return the excat json with nothing else
Thank you for your thorough and precise processing!
THEME_GENERATION_STATE: {generate_theme}
"""