-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtools.py
More file actions
204 lines (162 loc) · 4.94 KB
/
tools.py
File metadata and controls
204 lines (162 loc) · 4.94 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
"""
Custom tools for Job Application Assistant Agent
"""
import json
from pathlib import Path
from datetime import datetime
import google.generativeai as genai
from config import config
def llm(prompt: str, temperature: float = None, model: str = None) -> str:
"""
Call Google Gemini API with the given prompt.
Args:
prompt (str): The prompt to send to the AI
temperature (float): Controls randomness (0.0-1.0)
model (str): Gemini model to use
Returns:
str: AI-generated response
"""
if temperature is None:
temperature = config.temperature
if model is None:
model = config.worker_model
try:
llm_model = genai.GenerativeModel(model)
response = llm_model.generate_content(
prompt,
generation_config=genai.types.GenerationConfig(
temperature=temperature,
)
)
return response.text
except Exception as e:
error_msg = f"[Gemini API Error] {str(e)}"
print(error_msg)
raise RuntimeError(error_msg)
def read_text_file(file_path: str) -> dict:
"""
Reads a text file and returns its content.
Args:
file_path (str): Path to the text file
Returns:
dict: Dictionary with status and content
"""
try:
path = Path(file_path)
if not path.exists():
return {
"status": "error",
"error": f"File not found: {file_path}"
}
content = path.read_text(encoding='utf-8')
return {
"status": "success",
"content": content,
"file_path": str(path)
}
except Exception as e:
return {
"status": "error",
"error": str(e)
}
def save_json_file(data: dict, output_path: str) -> dict:
"""
Save data to JSON file.
Args:
data (dict): Data to save
output_path (str): Path to save the JSON file
Returns:
dict: Dictionary with status and file path
"""
try:
output = Path(output_path)
output.parent.mkdir(parents=True, exist_ok=True)
with open(output, 'w', encoding='utf-8') as f:
json.dump(data, f, indent=2, ensure_ascii=False)
return {
"status": "success",
"file_path": str(output)
}
except Exception as e:
return {
"status": "error",
"error": str(e)
}
def save_text_file(content: str, output_path: str) -> dict:
"""
Save text content to file.
Args:
content (str): Text content to save
output_path (str): Path to save the file
Returns:
dict: Dictionary with status and file path
"""
try:
output = Path(output_path)
output.parent.mkdir(parents=True, exist_ok=True)
with open(output, 'w', encoding='utf-8') as f:
f.write(content)
return {
"status": "success",
"file_path": str(output)
}
except Exception as e:
return {
"status": "error",
"error": str(e)
}
def create_output_directory(base_dir: str = "outputs") -> dict:
"""
Create timestamped output directory.
Args:
base_dir (str): Base directory for outputs
Returns:
dict: Dictionary with status and directory path
"""
try:
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
output_dir = Path(base_dir) / timestamp
output_dir.mkdir(parents=True, exist_ok=True)
return {
"status": "success",
"directory": str(output_dir)
}
except Exception as e:
return {
"status": "error",
"error": str(e)
}
def clean_json_response(response: str) -> str:
"""
Clean AI response to extract valid JSON.
Args:
response (str): Raw AI response
Returns:
str: Cleaned JSON string
"""
response = response.strip()
# Remove markdown code blocks
if response.startswith("```json"):
response = response[7:]
elif response.startswith("```"):
response = response[3:]
if response.endswith("```"):
response = response[:-3]
return response.strip()
def parse_json_response(response: str) -> dict:
"""
Parse AI response as JSON with error handling.
Args:
response (str): Raw AI response
Returns:
dict: Parsed JSON data
Raises:
ValueError: If JSON parsing fails
"""
cleaned = clean_json_response(response)
try:
return json.loads(cleaned)
except json.JSONDecodeError as e:
print(f"Error parsing JSON response: {e}")
print(f"Response was: {cleaned[:500]}")
raise ValueError("Failed to parse AI response as JSON")