ak0601 commited on
Commit
366097c
·
verified ·
1 Parent(s): b3d550c

Upload 2 files

Browse files
Files changed (2) hide show
  1. app_copy.py +569 -0
  2. requirements.txt +9 -0
app_copy.py ADDED
@@ -0,0 +1,569 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import json
3
+ from typing import List, Dict, Any, Optional
4
+ from pydantic import BaseModel, Field
5
+ from fastapi import FastAPI, HTTPException, Depends, Header
6
+ from fastapi.responses import JSONResponse
7
+ from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials
8
+ from enum import Enum
9
+ from dotenv import load_dotenv
10
+
11
+ load_dotenv()
12
+
13
+ # LangChain and OpenAI imports
14
+ try:
15
+ from langchain_openai import ChatOpenAI
16
+ from langchain.prompts import ChatPromptTemplate
17
+ from langchain.output_parsers import PydanticOutputParser
18
+ from langchain_core.pydantic_v1 import BaseModel as LangChainBaseModel, Field as LangChainField
19
+ LANGCHAIN_AVAILABLE = True
20
+ except ImportError:
21
+ LANGCHAIN_AVAILABLE = False
22
+ print("Warning: LangChain not available. Install with: pip install langchain langchain-openai")
23
+
24
+ # Security configuration
25
+ API_KEY = os.getenv("API_KEY")
26
+ security = HTTPBearer()
27
+
28
+ # Initialize FastAPI app
29
+ app = FastAPI(title="Job Candidate Email Template Generator", version="1.0.0")
30
+
31
+ # Security dependency
32
+ async def verify_api_key(credentials: HTTPAuthorizationCredentials = Depends(security)):
33
+ """Verify the API key from the Authorization header"""
34
+ if credentials.credentials != API_KEY:
35
+ raise HTTPException(
36
+ status_code=401,
37
+ detail="Invalid API key. Please provide a valid API key in the Authorization header.",
38
+ headers={"WWW-Authenticate": "Bearer"},
39
+ )
40
+ return credentials.credentials
41
+
42
+ # Enums for sequence types
43
+ class SequenceType(str, Enum):
44
+ INITIAL_OUTREACH = "initial_outreach"
45
+ FOLLOW_UP = "follow_up"
46
+ REPLY_TO_RESPONSE = "reply_to_response"
47
+
48
+ class ConversationMessage(BaseModel):
49
+ sender: str = Field(..., description="Who sent the message (candidate/recruiter)")
50
+ content: str = Field(..., description="Message content")
51
+ timestamp: Optional[str] = Field(None, description="Message timestamp")
52
+
53
+ # Data Models
54
+ class EmailTemplate(BaseModel):
55
+ subject: Optional[str] = Field(None, description="Email subject line (only for initial outreach)")
56
+ body: str = Field(..., description="Email body content with HTML formatting")
57
+ variant: str = Field(..., description="Template variant (A, B, or C)")
58
+ sequence_type: str = Field(..., description="Type of email sequence")
59
+
60
+ class GenerateTemplatesRequest(BaseModel):
61
+ job_description: Optional[str] = Field(None, description="Job description to generate email templates for")
62
+ company_name: Optional[str] = Field(None, description="Company name (optional)")
63
+ role_title: Optional[str] = Field(None, description="Job title/role (optional)")
64
+ salary_range: Optional[str] = Field(None, description="Salary range (optional)")
65
+ location: Optional[str] = Field(None, description="Job location (optional)")
66
+ tech_stack: Optional[str] = Field(None, description="Technology stack (optional)")
67
+ sequence_type: SequenceType = Field(SequenceType.INITIAL_OUTREACH, description="Type of email sequence to generate")
68
+ conversation_history: Optional[List[ConversationMessage]] = Field(None, description="Previous conversation messages for reply generation")
69
+ candidate_response: Optional[str] = Field(None, description="Candidate's response for follow-up generation")
70
+ days_since_last_contact: Optional[int] = Field(None, description="Days since last contact (for follow-ups)")
71
+
72
+ class GenerateTemplatesResponse(BaseModel):
73
+ success: bool = Field(..., description="Whether the generation was successful")
74
+ templates: List[EmailTemplate] = Field(..., description="Generated email templates")
75
+ message: str = Field(..., description="Response message")
76
+
77
+ # LangChain Pydantic models for structured output
78
+ class EmailTemplateStructured(LangChainBaseModel):
79
+ """Single email template for LangChain structured output"""
80
+ subject: Optional[str] = LangChainField(None, description="Engaging email subject line (only for initial outreach)")
81
+ body: str = LangChainField(description="HTML formatted email body with <br>, <p>, <strong> tags and {{first_name}} placeholder")
82
+
83
+ class EmailTemplatesStructured(LangChainBaseModel):
84
+ """All three email templates for LangChain structured output"""
85
+ template_a: EmailTemplateStructured = LangChainField(description="Direct and professional approach template")
86
+ template_b: EmailTemplateStructured = LangChainField(description="Casual and conversational approach template")
87
+ template_c: EmailTemplateStructured = LangChainField(description="Value-focused approach highlighting benefits template")
88
+
89
+ async def generate_email_templates_with_llm(request: GenerateTemplatesRequest) -> List[EmailTemplate]:
90
+ """Generate email templates using LangChain and OpenAI based on job description and sequence type"""
91
+
92
+ if not LANGCHAIN_AVAILABLE:
93
+ raise HTTPException(status_code=500, detail="LangChain not available. Please install langchain and langchain-openai")
94
+
95
+ try:
96
+ # Initialize OpenAI client
97
+ openai_api_key = os.getenv("OPENAI_API_KEY")
98
+ if not openai_api_key:
99
+ raise HTTPException(status_code=500, detail="OPENAI_API_KEY not set in environment variables")
100
+
101
+ # Initialize LLM with structured output
102
+ llm = ChatOpenAI(
103
+ model="gpt-4o-mini",
104
+ temperature=0.7,
105
+ openai_api_key=openai_api_key
106
+ )
107
+
108
+ # Configure LLM to use structured output
109
+ structured_llm = llm.with_structured_output(EmailTemplatesStructured)
110
+
111
+ # Get appropriate system prompt based on sequence type
112
+ system_prompt = get_system_prompt_for_sequence_type(request.sequence_type)
113
+
114
+ # Build context based on sequence type
115
+ context = build_context_for_sequence_type(request)
116
+
117
+ # Create the prompt template
118
+ prompt_template = ChatPromptTemplate.from_messages([
119
+ ("system", system_prompt),
120
+ ("human", "Generate email templates for this situation:\n\n{context}")
121
+ ])
122
+
123
+ # Create the chain
124
+ chain = prompt_template | structured_llm
125
+
126
+ # Generate the structured output
127
+ result = await chain.ainvoke({"context": context})
128
+
129
+ print(f"Structured output received successfully for {request.sequence_type}")
130
+
131
+ # Convert structured output to EmailTemplate objects
132
+ templates = [
133
+ EmailTemplate(
134
+ subject=result.template_a.subject,
135
+ body=result.template_a.body,
136
+ variant="A",
137
+ sequence_type=request.sequence_type.value
138
+ ),
139
+ EmailTemplate(
140
+ subject=result.template_b.subject,
141
+ body=result.template_b.body,
142
+ variant="B",
143
+ sequence_type=request.sequence_type.value
144
+ ),
145
+ EmailTemplate(
146
+ subject=result.template_c.subject,
147
+ body=result.template_c.body,
148
+ variant="C",
149
+ sequence_type=request.sequence_type.value
150
+ )
151
+ ]
152
+
153
+ return templates
154
+
155
+ except Exception as e:
156
+ print(f"Error generating templates with LLM: {str(e)}")
157
+ # Fallback to basic templates if LLM fails
158
+ return create_fallback_templates(request)
159
+
160
+ def get_system_prompt_for_sequence_type(sequence_type: SequenceType) -> str:
161
+ """Get appropriate system prompt based on sequence type"""
162
+
163
+ base_prompt = """You are an expert recruitment email template generator, your name is Ali Taghikhani, CEO of SRN. Create 3 different email templates (A, B, C) for recruitment communication.
164
+
165
+ Each template should be professional, personalized, and follow this structure:
166
+ - Body: HTML-formatted email with proper <br> tags and <p> tags
167
+ - Include placeholders like {{first_name}} for personalization
168
+ - Professional but friendly tone
169
+ - Clear call-to-action
170
+ - Focus on building interest and trust
171
+
172
+
173
+ Template Guidelines:
174
+ 1. Template A: Direct and professional approach - straight to the point, formal but friendly
175
+ 2. Template B: More casual and conversational approach - friendly, informal, relatable
176
+ 3. Template C: Value-focused approach highlighting benefits - emphasize growth, culture, perks
177
+
178
+ Use this sample structure as inspiration but create unique variations:
179
+ - Start with personalized greeting using {{first_name}}
180
+ - Brief introduction and reason for reaching out
181
+ - Key details about the role and company
182
+ - Clear call-to-action
183
+ - Professional sign-off
184
+
185
+ Make sure each template has a distinctly different tone and approach while maintaining professionalism."""
186
+
187
+ if sequence_type == SequenceType.INITIAL_OUTREACH:
188
+ return base_prompt + """
189
+
190
+ SPECIFIC GUIDELINES FOR INITIAL OUTREACH:
191
+ - This is the first contact with the candidate
192
+ - Include engaging subject lines for each template
193
+ - Focus on introducing the opportunity and building initial interest
194
+ - Don't mention salary range unless specifically provided
195
+ - Emphasize the role, company culture, and growth opportunities
196
+ - Make it easy for them to respond with their CV and interest"""
197
+
198
+ elif sequence_type == SequenceType.FOLLOW_UP:
199
+ return base_prompt + """
200
+
201
+ SPECIFIC GUIDELINES FOR FOLLOW-UP EMAILS:
202
+ - This is a follow-up to a previous outreach that didn't get a response
203
+ - Do not include subject lines (these are reply emails) keep that empty
204
+ - Be polite and not pushy - acknowledge they might be busy
205
+ - Reference the previous contact and the opportunity
206
+ - Offer additional value or information
207
+ - Give them an easy way to respond or opt out
208
+ - Consider the timing (mention if it's been a few days/weeks)
209
+ - Keep it brief and respectful"""
210
+
211
+ elif sequence_type == SequenceType.REPLY_TO_RESPONSE:
212
+ return base_prompt + """
213
+
214
+ SPECIFIC GUIDELINES FOR REPLYING TO CANDIDATE RESPONSES:
215
+ - This is a reply to a candidate who has responded to your outreach
216
+ - Do NOT include subject lines (these are reply emails) keep that empty
217
+ - Acknowledge their response and show enthusiasm
218
+ - Address any questions or concerns they raised
219
+ - Provide next steps in the process
220
+ - Be responsive to their level of interest
221
+ - Maintain the conversation flow naturally
222
+ - If they're interested, guide them to the next step
223
+ - If they're not interested, thank them politely and keep the door open"""
224
+
225
+ return base_prompt
226
+
227
+ def build_context_for_sequence_type(request: GenerateTemplatesRequest) -> str:
228
+ """Build appropriate context based on sequence type"""
229
+
230
+ # Base job information
231
+ context_parts = []
232
+
233
+ if request.job_description:
234
+ context_parts.append(f"Job Description: {request.job_description}")
235
+ else:
236
+ context_parts.append("Job Description: General recruitment opportunity")
237
+
238
+ if request.company_name:
239
+ context_parts.append(f"Company: {request.company_name}")
240
+ if request.role_title:
241
+ context_parts.append(f"Role: {request.role_title}")
242
+ if request.salary_range:
243
+ context_parts.append(f"Salary: {request.salary_range}")
244
+ if request.location:
245
+ context_parts.append(f"Location: {request.location}")
246
+ if request.tech_stack:
247
+ context_parts.append(f"Tech Stack: {request.tech_stack}")
248
+
249
+ # Add sequence-specific context
250
+ if request.sequence_type == SequenceType.FOLLOW_UP:
251
+ if request.days_since_last_contact:
252
+ context_parts.append(f"Days since last contact: {request.days_since_last_contact}")
253
+ if request.candidate_response:
254
+ context_parts.append(f"Previous candidate response: {request.candidate_response}")
255
+ context_parts.append("This is a follow-up email to a candidate who hasn't responded to the initial outreach.")
256
+
257
+ elif request.sequence_type == SequenceType.REPLY_TO_RESPONSE:
258
+ if request.conversation_history:
259
+ context_parts.append("Conversation History:")
260
+ for msg in request.conversation_history:
261
+ context_parts.append(f"- {msg.sender}: {msg.content}")
262
+ if request.candidate_response:
263
+ context_parts.append(f"Latest candidate response: {request.candidate_response}")
264
+ context_parts.append("This is a reply to a candidate who has responded to your outreach.")
265
+
266
+ return "\n".join(context_parts)
267
+
268
+ def create_fallback_templates(request: GenerateTemplatesRequest) -> List[EmailTemplate]:
269
+ """Create fallback email templates when LLM fails"""
270
+
271
+ # Build job info string
272
+ job_info_parts = []
273
+
274
+ if request.job_description:
275
+ job_info_parts.append(request.job_description)
276
+ else:
277
+ job_info_parts.append("exciting opportunity")
278
+
279
+ if request.company_name:
280
+ job_info_parts.insert(0, f"Company: {request.company_name}")
281
+ if request.role_title:
282
+ job_info_parts.insert(1, f"Role: {request.role_title}")
283
+ if request.salary_range:
284
+ job_info_parts.append(f"Salary: {request.salary_range}")
285
+ if request.location:
286
+ job_info_parts.append(f"Location: {request.location}")
287
+ if request.tech_stack:
288
+ job_info_parts.append(f"Tech Stack: {request.tech_stack}")
289
+
290
+ job_info = "<br>".join(job_info_parts)
291
+
292
+ # Create templates based on sequence type
293
+ templates = []
294
+
295
+ if request.sequence_type == SequenceType.INITIAL_OUTREACH:
296
+ # Template A: Direct approach
297
+ templates.append(EmailTemplate(
298
+ subject="Exciting Opportunity: Senior Developer Position Available",
299
+ body=f"""<p>Hi {{{{first_name}}}},</p>
300
+ <p>I'm reaching out because I have an opportunity that aligns perfectly with your experience and expertise.</p>
301
+ <p>{job_info}</p>
302
+ <p>If this sounds interesting to you, I'd love to discuss the details further. Please send me your updated CV and salary expectations, and I'll fast-track your application to the hiring team.</p>
303
+ <p>Best regards,<br>
304
+ [Your Name]<br>
305
+ [Your Title]</p>""",
306
+ variant="A",
307
+ sequence_type=request.sequence_type.value
308
+ ))
309
+
310
+ # Template B: Casual approach
311
+ templates.append(EmailTemplate(
312
+ subject="Quick question about your next career move 🚀",
313
+ body=f"""<p>Hey {{{{first_name}}}},</p>
314
+ <p>Hope you're having a great day! I came across your profile and thought you might be interested in something exciting.</p>
315
+ <p>{job_info}</p>
316
+ <p>The team is amazing, and they're looking for someone just like you. Want to chat about it? Just shoot me your CV and let me know what you're looking for in your next role.</p>
317
+ <p>Cheers,<br>
318
+ [Your Name]</p>""",
319
+ variant="B",
320
+ sequence_type=request.sequence_type.value
321
+ ))
322
+
323
+ # Template C: Value-focused approach
324
+ templates.append(EmailTemplate(
325
+ subject="Transform Your Career: Join a Leading Tech Team",
326
+ body=f"""<p>Hi {{{{first_name}}}},</p>
327
+ <p>I'm reaching out with an opportunity that offers exceptional growth potential and the chance to work with cutting-edge technologies.</p>
328
+ <p>{job_info}</p>
329
+ <p><strong>Why this role stands out:</strong><br>
330
+ • Work with the latest technologies<br>
331
+ • Competitive compensation and benefits<br>
332
+ • Flexible work arrangements<br>
333
+ • Clear career progression path</p>
334
+ <p>If you're ready to take your career to the next level, I'd love to share more details. Please send me your resume and salary requirements.</p>
335
+ <p>Looking forward to connecting,<br>
336
+ [Your Name]<br>
337
+ [Your Title]</p>""",
338
+ variant="C",
339
+ sequence_type=request.sequence_type.value
340
+ ))
341
+
342
+ elif request.sequence_type == SequenceType.FOLLOW_UP:
343
+ days_text = f" {request.days_since_last_contact} days ago" if request.days_since_last_contact else ""
344
+
345
+ # Template A: Polite follow-up
346
+ templates.append(EmailTemplate(
347
+ subject="",
348
+ body=f"""<p>Hi {{{{first_name}}}},</p>
349
+ <p>I hope this email finds you well. I wanted to follow up on the opportunity I reached out about{days_text}.</p>
350
+ <p>{job_info}</p>
351
+ <p>I understand you're likely busy, but I wanted to make sure you had all the information you need. If you're interested, I'd be happy to discuss this further. If not, no worries at all - just let me know either way!</p>
352
+ <p>Best regards,<br>
353
+ [Your Name]</p>""",
354
+ variant="A",
355
+ sequence_type=request.sequence_type.value
356
+ ))
357
+
358
+ # Template B: Casual follow-up
359
+ templates.append(EmailTemplate(
360
+ subject="",
361
+ body=f"""<p>Hey {{{{first_name}}}},</p>
362
+ <p>Just wanted to check in and see if you had a chance to look at the opportunity I mentioned{days_text}.</p>
363
+ <p>{job_info}</p>
364
+ <p>No pressure at all - just wanted to make sure you didn't miss it! Let me know if you're interested or if you have any questions.</p>
365
+ <p>Cheers,<br>
366
+ [Your Name]</p>""",
367
+ variant="B",
368
+ sequence_type=request.sequence_type.value
369
+ ))
370
+
371
+ # Template C: Value-added follow-up
372
+ templates.append(EmailTemplate(
373
+ subject="",
374
+ body=f"""<p>Hi {{{{first_name}}}},</p>
375
+ <p>I hope you're doing well. I wanted to follow up on the opportunity I shared{days_text} and provide some additional context.</p>
376
+ <p>{job_info}</p>
377
+ <p><strong>What's new:</strong><br>
378
+ • The team is growing rapidly<br>
379
+ • New exciting projects are starting soon<br>
380
+ • Flexible work arrangements available</p>
381
+ <p>If this sounds interesting, I'd love to discuss it further. If not, I completely understand!</p>
382
+ <p>Best regards,<br>
383
+ [Your Name]</p>""",
384
+ variant="C",
385
+ sequence_type=request.sequence_type.value
386
+ ))
387
+
388
+ elif request.sequence_type == SequenceType.REPLY_TO_RESPONSE:
389
+ # Template A: Professional reply
390
+ templates.append(EmailTemplate(
391
+ subject="",
392
+ body=f"""<p>Hi {{{{first_name}}}},</p>
393
+ <p>Thank you for your response! I'm excited to hear about your interest.</p>
394
+ <p>{job_info}</p>
395
+ <p>Next steps would be to schedule a brief call to discuss the role in more detail and answer any questions you might have. When would be a good time for you?</p>
396
+ <p>Looking forward to our conversation,<br>
397
+ [Your Name]</p>""",
398
+ variant="A",
399
+ sequence_type=request.sequence_type.value
400
+ ))
401
+
402
+ # Template B: Friendly reply
403
+ templates.append(EmailTemplate(
404
+ subject="",
405
+ body=f"""<p>Hey {{{{first_name}}}},</p>
406
+ <p>Awesome! Thanks for getting back to me. I'm glad you're interested.</p>
407
+ <p>{job_info}</p>
408
+ <p>Let's set up a quick chat to go over the details and see if it's a good fit. What's your schedule like this week?</p>
409
+ <p>Talk soon,<br>
410
+ [Your Name]</p>""",
411
+ variant="B",
412
+ sequence_type=request.sequence_type.value
413
+ ))
414
+
415
+ # Template C: Detailed reply
416
+ templates.append(EmailTemplate(
417
+ subject="",
418
+ body=f"""<p>Hi {{{{first_name}}}},</p>
419
+ <p>Excellent! Thank you for your interest. I'm looking forward to discussing this opportunity with you.</p>
420
+ <p>{job_info}</p>
421
+ <p><strong>What happens next:</strong><br>
422
+ • Brief 15-minute call to discuss the role<br>
423
+ • Technical assessment (if interested)<br>
424
+ • Team interview<br>
425
+ • Offer discussion</p>
426
+ <p>When would be convenient for you to have our initial call?</p>
427
+ <p>Best regards,<br>
428
+ [Your Name]</p>""",
429
+ variant="C",
430
+ sequence_type=request.sequence_type.value
431
+ ))
432
+
433
+ return templates
434
+
435
+ @app.post("/generate-email-templates", response_model=GenerateTemplatesResponse)
436
+ async def generate_email_templates(request: GenerateTemplatesRequest, api_key: str = Depends(verify_api_key)):
437
+ """Generate 3 variants of email templates for job candidates
438
+
439
+ This endpoint generates professional email templates for different types of recruitment communication
440
+ based on the provided parameters and sequence type.
441
+
442
+ Parameters:
443
+ - job_description: Detailed description of the job/role (optional, defaults to general opportunity)
444
+ - company_name: Name of the company (optional)
445
+ - role_title: Job title/role (optional)
446
+ - salary_range: Salary range (optional)
447
+ - location: Job location (optional)
448
+ - tech_stack: Technology stack (optional)
449
+ - sequence_type: Type of email sequence (initial_outreach, follow_up, reply_to_response) - defaults to initial_outreach
450
+ - conversation_history: Previous conversation messages for reply generation (optional)
451
+ - candidate_response: Candidate's response for follow-up generation (optional)
452
+ - days_since_last_contact: Days since last contact for follow-ups (optional)
453
+
454
+ Returns:
455
+ - 3 email templates (A, B, C) with different approaches and tones based on sequence type
456
+ """
457
+
458
+ try:
459
+ # Generate templates using LLM
460
+ templates = await generate_email_templates_with_llm(request)
461
+
462
+ return GenerateTemplatesResponse(
463
+ success=True,
464
+ templates=templates,
465
+ message=f"Successfully generated {len(templates)} email templates"
466
+ )
467
+
468
+ except HTTPException:
469
+ # Re-raise HTTP exceptions
470
+ raise
471
+ except Exception as e:
472
+ raise HTTPException(status_code=500, detail=f"Unexpected error: {str(e)}")
473
+
474
+ @app.get("/health")
475
+ async def health_check():
476
+ """Health check endpoint (no authentication required)"""
477
+ return {"status": "healthy", "langchain_available": LANGCHAIN_AVAILABLE}
478
+
479
+ @app.get("/health/secure")
480
+ async def health_check_secure(api_key: str = Depends(verify_api_key)):
481
+ """Secure health check endpoint (requires API key)"""
482
+ return {
483
+ "status": "healthy",
484
+ "langchain_available": LANGCHAIN_AVAILABLE,
485
+ "api_key_valid": True
486
+ }
487
+
488
+ @app.get("/")
489
+ async def root():
490
+ """Root endpoint with API information"""
491
+ return {
492
+ "message": "Job Candidate Email Template Generator API",
493
+ "version": "1.0.0",
494
+ "authentication": {
495
+ "type": "Bearer Token",
496
+ "required": "Yes (for /generate-email-templates and /health/secure)",
497
+ "header": "Authorization: Bearer <api_key>"
498
+ },
499
+ "endpoints": {
500
+ "generate_templates": "/generate-email-templates (requires API key)",
501
+ "health": "/health (no auth required)",
502
+ "health_secure": "/health/secure (requires API key)"
503
+ },
504
+ "usage": {
505
+ "POST /generate-email-templates": "Generate 3 email template variants for different recruitment scenarios"
506
+ },
507
+ "sequence_types": {
508
+ "initial_outreach": "First contact with potential candidates",
509
+ "follow_up": "Follow-up emails for candidates who haven't responded",
510
+ "reply_to_response": "Replies to candidates who have responded to outreach"
511
+ }
512
+ }
513
+
514
+ # Example usage for testing
515
+ if __name__ == "__main__":
516
+ import uvicorn
517
+
518
+ # Example requests for testing different sequence types
519
+ example_requests = {
520
+ "minimal_request": {
521
+ "sequence_type": "initial_outreach"
522
+ },
523
+ "initial_outreach": {
524
+ "job_description": "We're looking for a Senior Full-Stack Developer to join our growing team.",
525
+ "company_name": "TechCorp",
526
+ "role_title": "Senior Full-Stack Developer",
527
+ "salary_range": "€80,000 - €100,000",
528
+ "location": "Remote (EU timezone)",
529
+ "tech_stack": "React, Node.js, PostgreSQL, AWS",
530
+ "sequence_type": "initial_outreach"
531
+ },
532
+ "follow_up": {
533
+ "job_description": "We're looking for a Senior Full-Stack Developer to join our growing team.",
534
+ "company_name": "TechCorp",
535
+ "role_title": "Senior Full-Stack Developer",
536
+ "salary_range": "€80,000 - €100,000",
537
+ "location": "Remote (EU timezone)",
538
+ "tech_stack": "React, Node.js, PostgreSQL, AWS",
539
+ "sequence_type": "follow_up",
540
+ "days_since_last_contact": 7
541
+ },
542
+ "reply_to_response": {
543
+ "job_description": "We're looking for a Senior Full-Stack Developer to join our growing team.",
544
+ "company_name": "TechCorp",
545
+ "role_title": "Senior Full-Stack Developer",
546
+ "salary_range": "€80,000 - €100,000",
547
+ "location": "Remote (EU timezone)",
548
+ "tech_stack": "React, Node.js, PostgreSQL, AWS",
549
+ "sequence_type": "reply_to_response",
550
+ "conversation_history": [
551
+ {
552
+ "sender": "recruiter",
553
+ "content": "Hi John, I have an exciting opportunity for a Senior Full-Stack Developer role at TechCorp."
554
+ },
555
+ {
556
+ "sender": "candidate",
557
+ "content": "Hi Ali, thanks for reaching out! I'm definitely interested. Could you tell me more about the team and the tech stack?"
558
+ }
559
+ ],
560
+ "candidate_response": "Hi Ali, thanks for reaching out! I'm definitely interested. Could you tell me more about the team and the tech stack?"
561
+ }
562
+ }
563
+
564
+ print("Example requests for different sequence types:")
565
+ for seq_type, request in example_requests.items():
566
+ print(f"\n{seq_type.upper()}:")
567
+ print(json.dumps(request, indent=2))
568
+
569
+ uvicorn.run(app, host="0.0.0.0", port=8000)
requirements.txt ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ fastapi==0.116.1
2
+ httpx==0.28.1
3
+ langchain==0.3.26
4
+ langchain_core==0.3.69
5
+ langchain_openai==0.3.28
6
+ pydantic==2.11.7
7
+ python-dotenv==1.1.1
8
+ Requests==2.32.4
9
+ uvicorn==0.35.0