-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path7_final.py
More file actions
174 lines (146 loc) · 4.81 KB
/
7_final.py
File metadata and controls
174 lines (146 loc) · 4.81 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
from fastapi import FastAPI, HTTPException
from pydantic import BaseModel
from dotenv import load_dotenv
import uuid
import os
import json
from database import SessionLocal, Interview
from llm import generate_response
load_dotenv()
app = FastAPI(
title="InterviewAI API",
description="AI-powered mock interview system with feedback",
version="1.0.0"
)
sessions = {}
class InterviewSetup(BaseModel):
name: str
experience: str
skills: str
level: str
position: str
company: str
provider: str = "openai" # default provider
class UserMessage(BaseModel):
message: str
@app.get("/")
def health_check():
return {"status": "running", "active_sessions": len(sessions)}
@app.post("/start-interview")
def start_interview(setup: InterviewSetup):
session_id = str(uuid.uuid4())
system_prompt = (
f"You are an HR executive interviewing {setup.name} "
f"who has experience: {setup.experience} and skills: {setup.skills}. "
f"Interview them for the position of {setup.level} {setup.position} "
f"at {setup.company}. "
f"Ask one question at a time. Be professional but friendly. "
f"Start by greeting them and asking them to introduce themselves."
)
sessions[session_id] = {
"setup": setup.model_dump(),
"provider": setup.provider,
"messages": [{"role": "system", "content": system_prompt}],
"message_count": 0,
"max_messages": 5,
}
assistant_msg = generate_response(
sessions[session_id]["messages"],
provider=sessions[session_id]["provider"]
)
sessions[session_id]["messages"].append(
{"role": "assistant", "content": assistant_msg}
)
db = SessionLocal()
db_interview = Interview(
id=session_id,
name=setup.name,
position=setup.position,
company=setup.company,
level=setup.level,
messages=json.dumps(sessions[session_id]["messages"])
)
db.add(db_interview)
db.commit()
db.close()
return {
"session_id": session_id,
"message": assistant_msg,
"messages_remaining": 5,
}
@app.post("/chat/{session_id}")
def chat(session_id: str, user_msg: UserMessage):
if session_id not in sessions:
raise HTTPException(status_code=404, detail="Session not found")
session = sessions[session_id]
if session["message_count"] >= session["max_messages"]:
raise HTTPException(status_code=400, detail="Interview complete. Get feedback.")
session["messages"].append({"role": "user", "content": user_msg.message})
session["message_count"] += 1
assistant_msg = ""
if session["message_count"] < session["max_messages"]:
assistant_msg = generate_response(
session["messages"],
provider=session["provider"]
)
session["messages"].append({"role": "assistant", "content": assistant_msg})
remaining = session["max_messages"] - session["message_count"]
return {
"message": assistant_msg if assistant_msg else "Interview complete! Get your feedback.",
"messages_remaining": remaining,
"interview_complete": remaining == 0,
}
@app.get("/feedback/{session_id}")
def get_feedback(session_id: str):
if session_id not in sessions:
raise HTTPException(status_code=404, detail="Session not found")
session = sessions[session_id]
conversation = "\n".join(
f"{m['role']}: {m['content']}"
for m in session["messages"]
if m["role"] != "system"
)
feedback_messages = [
{
"role": "system",
"content": """You are a helpful tool that provides
feedback on an interviewee's performance.
Follow this format:
Overall Score: [1-10]
Strengths: [list strengths]
Areas for Improvement: [list improvements]
Detailed Feedback: [your feedback]
Give only the feedback, do not ask questions."""
},
{
"role": "user",
"content": f"Evaluate this interview:\n{conversation}"
}
]
feedback = generate_response(
feedback_messages,
provider=session["provider"]
)
return {
"session_id": session_id,
"candidate": session["setup"]["name"],
"position": f"{session['setup']['level']} {session['setup']['position']}",
"company": session["setup"]["company"],
"feedback": feedback,
}
@app.get("/interviews")
def list_interviews():
db = SessionLocal()
interviews = db.query(Interview).order_by(Interview.created_at.desc()).all()
db.close()
return [
{
"id": i.id,
"name": i.name,
"position": f"{i.level} {i.position}",
"company": i.company,
"has_feedback": i.feedback is not None,
"created_at": str(i.created_at),
}
for i in interviews
]