-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathagent.py
More file actions
319 lines (267 loc) · 12.3 KB
/
agent.py
File metadata and controls
319 lines (267 loc) · 12.3 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
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
"""
Job Application Assistant Agent - Main Orchestrator
Coordinates sub-agents to generate job application materials
"""
import datetime
from pathlib import Path
from typing import Dict, Any, Optional
from config import config
from tools import (
read_text_file,
save_json_file,
save_text_file,
create_output_directory
)
from agent_utils import (
format_profile_summary,
format_job_summary,
print_step_header,
print_success_message,
print_error_message
)
from sub_agents.profile_parser import profile_parser_agent
from sub_agents.job_parser import job_parser_agent
from sub_agents.cv_generator import cv_generator_agent
from sub_agents.cover_letter_generator import cover_letter_generator_agent
from sub_agents.latex_cv_generator import latex_cv_generator_agent
from sub_agents.latex_cover_letter_generator import latex_cover_letter_generator_agent
from validation_checkers import validate_all
class JobAssistantAgent:
"""
Main agent that orchestrates the entire job application generation process.
This agent follows a structured workflow:
1. Parse user profile
2. Parse job posting
3. Generate tailored CV
4. Generate personalized cover letter
5. Save all outputs
"""
def __init__(self):
"""Initialize the Job Assistant Agent."""
self.config = config
self.user_profile: Optional[Dict] = None
self.job_posting: Optional[Dict] = None
self.cv_content: Optional[str] = None
self.cover_letter: Optional[str] = None
self.output_directory: Optional[str] = None
def run(
self,
profile_path: str,
job_path: str,
output_dir: str = "outputs",
cv_format: str = "text",
generate_cv: bool = True,
generate_cover_letter: bool = True,
latex_output: bool = False,
with_photo: bool = False,
photo_path: Optional[str] = None
) -> Dict[str, Any]:
"""
Run the complete job application generation workflow.
Args:
profile_path (str): Path to user profile text file
job_path (str): Path to job posting text file
output_dir (str): Base output directory
cv_format (str): CV format ('text' or 'markdown')
generate_cv (bool): Whether to generate CV
generate_cover_letter (bool): Whether to generate cover letter
latex_output (bool): Whether to generate LaTeX/PDF output
with_photo (bool): Whether to include photo in LaTeX CV
photo_path (str): Path to photo file (required if with_photo=True)
Returns:
Dict[str, Any]: Results including paths to generated files
"""
results = {
"status": "running",
"files": [],
"errors": []
}
try:
# Step 1: Parse user profile
print_step_header(1, "PARSING USER PROFILE")
profile_result = read_text_file(profile_path)
if profile_result['status'] == 'error':
raise FileNotFoundError(profile_result['error'])
self.user_profile = profile_parser_agent(profile_result['content'])
print(format_profile_summary(self.user_profile))
# Step 2: Parse job posting
print_step_header(2, "PARSING JOB POSTING")
job_result = read_text_file(job_path)
if job_result['status'] == 'error':
raise FileNotFoundError(job_result['error'])
self.job_posting = job_parser_agent(job_result['content'])
print(format_job_summary(self.job_posting))
# Create output directory
dir_result = create_output_directory(output_dir)
if dir_result['status'] == 'error':
raise RuntimeError(dir_result['error'])
self.output_directory = dir_result['directory']
print(f"\nOutput directory: {self.output_directory}")
# Save parsed data
profile_json_path = str(Path(self.output_directory) / "parsed_profile.json")
job_json_path = str(Path(self.output_directory) / "parsed_job.json")
save_json_file(self.user_profile, profile_json_path)
save_json_file(self.job_posting, job_json_path)
results['files'].extend([profile_json_path, job_json_path])
# Step 3: Generate CV
if generate_cv:
print_step_header(3, "GENERATING CV")
# Generate text/markdown CV
self.cv_content = cv_generator_agent(
self.user_profile,
self.job_posting,
cv_format
)
# Save CV
name = self.user_profile['personal_info']['full_name'].replace(' ', '_')
cv_filename = f"CV_{name}.{'md' if cv_format == 'markdown' else 'txt'}"
cv_path = str(Path(self.output_directory) / cv_filename)
cv_save_result = save_text_file(self.cv_content, cv_path)
if cv_save_result['status'] == 'success':
print_success_message(f"CV saved to: {cv_path}")
results['files'].append(cv_path)
# Generate LaTeX CV if requested
if latex_output:
print("\nGenerating LaTeX/PDF CV...")
latex_cv_path = str(Path(self.output_directory) / f"CV_{name}.tex")
latex_cv_result = latex_cv_generator_agent(
config=self.config,
profile_data=self.user_profile,
job_data=self.job_posting,
output_path=latex_cv_path,
with_photo=with_photo,
photo_path=photo_path
)
if latex_cv_result['success']:
results['files'].append(latex_cv_result['tex_path'])
if latex_cv_result['pdf_path']:
results['files'].append(latex_cv_result['pdf_path'])
print_success_message(f"PDF CV saved to: {latex_cv_result['pdf_path']}")
else:
print_error_message(f"LaTeX CV generation: {latex_cv_result.get('error', 'Unknown error')}")
# Step 4: Generate Cover Letter
if generate_cover_letter:
print_step_header(4, "GENERATING COVER LETTER")
# Generate text cover letter
self.cover_letter = cover_letter_generator_agent(
self.user_profile,
self.job_posting
)
# Save Cover Letter
name = self.user_profile['personal_info']['full_name'].replace(' ', '_')
cl_filename = f"CoverLetter_{name}.txt"
cl_path = str(Path(self.output_directory) / cl_filename)
cl_save_result = save_text_file(self.cover_letter, cl_path)
if cl_save_result['status'] == 'success':
print_success_message(f"Cover letter saved to: {cl_path}")
results['files'].append(cl_path)
# Generate LaTeX cover letter if requested
if latex_output:
print("\nGenerating LaTeX/PDF cover letter...")
latex_cl_path = str(Path(self.output_directory) / f"CoverLetter_{name}.tex")
latex_cl_result = latex_cover_letter_generator_agent(
config=self.config,
profile_data=self.user_profile,
job_data=self.job_posting,
output_path=latex_cl_path
)
if latex_cl_result['success']:
results['files'].append(latex_cl_result['tex_path'])
if latex_cl_result['pdf_path']:
results['files'].append(latex_cl_result['pdf_path'])
print_success_message(f"PDF cover letter saved to: {latex_cl_result['pdf_path']}")
else:
print_error_message(f"LaTeX cover letter generation: {latex_cl_result.get('error', 'Unknown error')}")
# Final validation
validation_results = validate_all(
user_profile=self.user_profile,
job_posting=self.job_posting,
cv_content=self.cv_content if generate_cv else None,
cover_letter=self.cover_letter if generate_cover_letter else None
)
# Save validation results
validation_path = str(Path(self.output_directory) / "validation_results.json")
save_json_file(validation_results, validation_path)
results['files'].append(validation_path)
results['status'] = 'success'
results['output_directory'] = self.output_directory
results['validation'] = validation_results
return results
except Exception as e:
print_error_message(str(e))
results['status'] = 'failed'
results['errors'].append(str(e))
return results
def print_summary(self, results: Dict[str, Any]):
"""
Print a summary of the generation process.
Args:
results (Dict[str, Any]): Results from the run method
"""
print("\n" + "="*70)
if results['status'] == 'success':
print("SUCCESS! APPLICATION MATERIALS GENERATED")
else:
print("FAILED TO GENERATE APPLICATION MATERIALS")
print("="*70)
if results.get('output_directory'):
print(f"\nAll files saved to: {results['output_directory']}")
print("\nGenerated files:")
for file in results.get('files', []):
filename = Path(file).name
print(f" • {filename}")
if results.get('errors'):
print("\nErrors:")
for error in results['errors']:
print(f" • {error}")
if results['status'] == 'success':
print("\n" + "="*70)
print("NEXT STEPS:")
print("="*70)
print("1. Review the generated CV and cover letter")
print("2. Make any necessary personal adjustments")
print("3. Save as PDF before submitting")
print("4. Good luck with your application!")
print("="*70 + "\n")
# Create the main agent instance
job_assistant_agent = JobAssistantAgent()
def run_job_assistant(
profile_path: str,
job_path: str,
output_dir: str = "outputs",
cv_format: str = "text",
generate_cv: bool = True,
generate_cover_letter: bool = True,
latex_output: bool = False,
with_photo: bool = False,
photo_path: Optional[str] = None
) -> Dict[str, Any]:
"""
Convenience function to run the job assistant agent.
Args:
profile_path (str): Path to user profile text file
job_path (str): Path to job posting text file
output_dir (str): Base output directory
cv_format (str): CV format ('text' or 'markdown')
generate_cv (bool): Whether to generate CV
generate_cover_letter (bool): Whether to generate cover letter
latex_output (bool): Whether to generate LaTeX/PDF output
with_photo (bool): Whether to include photo in LaTeX CV
photo_path (str): Path to photo file (required if with_photo=True)
Returns:
Dict[str, Any]: Results including paths to generated files
"""
agent = JobAssistantAgent()
results = agent.run(
profile_path=profile_path,
job_path=job_path,
output_dir=output_dir,
cv_format=cv_format,
generate_cv=generate_cv,
generate_cover_letter=generate_cover_letter,
latex_output=latex_output,
with_photo=with_photo,
photo_path=photo_path
)
agent.print_summary(results)
return results