-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
272 lines (215 loc) · 7.06 KB
/
Copy pathmain.py
File metadata and controls
272 lines (215 loc) · 7.06 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
from fastapi import FastAPI, HTTPException
from fastapi.middleware.cors import CORSMiddleware
from typing import Dict, List, Optional
from pydantic import BaseModel, Field, validator
from dotenv import load_dotenv
import os
import uuid
import json
# Langchain
from langchain_google_genai import ChatGoogleGenerativeAI
from langchain_core.prompts import ChatPromptTemplate
from langchain_core.output_parsers import StrOutputParser, JsonOutputParser
load_dotenv()
GEMINI_API_KEY = os.getenv("GEMINI")
# Parsers
str_parser = StrOutputParser()
json_parser = JsonOutputParser()
# LLM
llm = ChatGoogleGenerativeAI(
model='gemini-2.5-flash',
google_api_key = GEMINI_API_KEY
)
# Prompts
GENERATE_QUESTIONS_PROMPT = ChatPromptTemplate.from_template(
"""
You are an expert technical interviewer. Based on the job role and experience level, generate exactly 5 relevant technical questions.
Job Role: {job_role}
Experience Level: {experience} years
Generate 5 questions that are:
1. Appropriate for the experience level
2. Technical and role-specific
3. Progressive in difficulty
4. Cover different aspects of the role
Return ONLY a JSON array of 5 questions, no explanations:
[
"Question 1",
"Question 2",
"Question 3",
"Question 4",
"Question 5"
]
"""
)
EVALUATE_ANSWER_PROMPT = ChatPromptTemplate.from_template(
"""
You are an expert technical interviewer evaluating a candidate's answer.
Job Role: {job_role}
Experience Level: {experience} years
Question: {question}
Candidate's Answer: {answer}
Provide a detailed evaluation including:
1. Technical accuracy (1-10)
2. Completeness of answer (1-10)
3. Clarity of explanation (1-10)
4. Specific feedback and suggestions
5. Overall score (1-10)
Format your response as:
Score: X/10
Technical Accuracy: X/10
Completeness: X/10
Clarity: X/10
Feedback: [Your detailed feedback here]
"""
)
FINAL_REPORT_PROMPT = ChatPromptTemplate.from_template(
"""
You are an expert technical interviewer creating a comprehensive interview report.
Job Role: {job_role}
Experience Level: {experience} years
Interview Results:
{interview_results}
Create a professional final report including:
1. Overall assessment
2. Strengths identified
3. Areas for improvement
4. Technical competency score (average of all scores)
5. Recommendation (Pass/Fail/Consider with conditions)
6. Detailed breakdown of each question
Format as a professional report.
"""
)
def generate_questions(job_role: str, experience: int):
chain = GENERATE_QUESTIONS_PROMPT | llm | json_parser
questions = chain.invoke({"job_role": job_role, "experience": experience})
return questions
def evaluate_answer(job_role: str, experience: int, question: str, answer: str) -> str:
chain = EVALUATE_ANSWER_PROMPT | llm | str_parser
feedback = chain.invoke({
"job_role": job_role,
"experience": experience,
"question": question,
"answer": answer,
})
return feedback
def build_final_report(job_role: str, experience: int, data: List[dict]) -> str:
# Prepare interview results text blob similar to original script
interview_results = []
for i, row in enumerate(data, start=1):
interview_results.append(
f"Question {i}: {row.get('question','')}\nAnswer: {row.get('answer','')}\nFeedback: {row.get('feedback','')}\n"
+ ("-" * 40)
)
results_blob = "\n".join(interview_results)
chain = FINAL_REPORT_PROMPT | llm | str_parser
report = chain.invoke({
"job_role": job_role,
"experience": experience,
"interview_results": results_blob,
})
return report
# APP and CORS
app = FastAPI(
debug=True,
title="AI Interviewer API",
version="1.0.0"
)
# BaseModels
class CreateSessionRequest(BaseModel) :
job_role : str = Field(..., example="React Developer")
experience : int = Field(..., ge=0, le=50)
class CreateSessionResponse(BaseModel) :
session_id : str
job_role : str
experience : int
questions : list
current_que_idx : int
class SessionState(BaseModel) :
job_role : str
experience : int
data : List[dict]
current_que_idx : int
class SubmitAnswerRequest(BaseModel):
answer: str
class SubmitAnswerResponse(BaseModel):
question_idx: int
question: str
feedback: str
next_question_idx: Optional[int] = None
next_question: Optional[str] = None
# In-Memory Store ]
sessions: Dict[str, SessionState] = {}
@app.get("/")
def root() :
return {
'message' : "Root"
}
@app.get("/health")
async def health() :
return {
'status' : 'Health OK'
}
@app.post("/session", response_model=CreateSessionResponse, status_code=201)
async def create_session(payload : CreateSessionRequest) :
"""Create a new interview session and return only the session ID"""
sid = uuid.uuid4().hex
questions = generate_questions(payload.job_role, payload.experience)
state = SessionState(
job_role = payload.job_role,
experience=payload.experience,
data= [{"question": q, "answer": "", "feedback": ""} for q in questions],
current_question_idx=0
)
sessions[sid] = state
return CreateSessionResponse(
session_id=sid,
job_role=state.job_role,
experience=state.experience,
questions=[row["question"] for row in state.data],
current_que_idx=state.current_question_idx
)
@app.get("/session/{session_id}", response_model=SessionState)
async def get_session_state(session_id : str) :
current_state = sessions.get(session_id, None)
return current_state
@app.post("/sessions/{session_id}/answers", response_model=SubmitAnswerResponse)
async def submit_answer(session_id: str, payload: SubmitAnswerRequest):
state = sessions.get(session_id)
idx = state.current_question_idx
if idx >= 5:
raise HTTPException(status_code=400, detail="All questions already answered")
question = state.data[idx]["question"]
# Save the answer
state.data[idx]["answer"] = payload.answer.strip()
# Evaluate
feedback = evaluate_answer(state.job_role, state.experience, question, state.data[idx]["answer"])
state.data[idx]["feedback"] = feedback
# Move index
state.current_question_idx += 1
# Set next question info
next_q_idx = None
next_q = None
if state.current_question_idx < 5:
next_q_idx = state.current_question_idx
next_q = state.data[next_q_idx]["question"]
# Persist
sessions[session_id] = state
return SubmitAnswerResponse(
question_idx=idx,
question=question,
feedback=feedback,
next_question_idx=next_q_idx,
next_question=next_q,
)
@app.get("/sessions/{session_id}/report")
async def get_report(session_id: str):
state = sessions.get(session_id)
if not state:
raise HTTPException(status_code=404, detail="Session not found")
if state.current_question_idx < 5:
raise HTTPException(status_code=400, detail="Interview not yet complete")
return {
"job_role": state.job_role,
"experience": state.experience,
"final_report": state.final_report,
}