优化简历定制简历生产
This commit is contained in:
@@ -5,6 +5,7 @@
|
|||||||
"""
|
"""
|
||||||
|
|
||||||
import asyncio
|
import asyncio
|
||||||
|
import time
|
||||||
|
|
||||||
from langchain_core.output_parsers import StrOutputParser
|
from langchain_core.output_parsers import StrOutputParser
|
||||||
from langchain_core.prompts import ChatPromptTemplate
|
from langchain_core.prompts import ChatPromptTemplate
|
||||||
@@ -44,20 +45,23 @@ async def analyze_skill_gap(skill_tags: list[str], resume_json: str) -> list[str
|
|||||||
|
|
||||||
_summary_optimize_chain = (
|
_summary_optimize_chain = (
|
||||||
ChatPromptTemplate.from_messages([("system", SUMMARY_OPTIMIZE_PROMPT), ("human", "请开始优化。")])
|
ChatPromptTemplate.from_messages([("system", SUMMARY_OPTIMIZE_PROMPT), ("human", "请开始优化。")])
|
||||||
| LLM.JIAYU_CLAUDE_SONNET_4_5.create(temperature=0.3)
|
| LLM.DOUBAO_PRO_32K.create(temperature=0.3)
|
||||||
| StrOutputParser()
|
| StrOutputParser()
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
async def optimize_summary(job_title: str, add_skills: list[str], original_summary: str) -> str:
|
async def optimize_summary(job_title: str, add_skills: list[str], original_summary: str) -> str:
|
||||||
"""优化个人概述,融入技能关键词"""
|
"""优化个人概述,融入技能关键词"""
|
||||||
|
t0 = time.monotonic()
|
||||||
try:
|
try:
|
||||||
return await _summary_optimize_chain.ainvoke({
|
result = await _summary_optimize_chain.ainvoke({
|
||||||
"job_title": job_title, "add_skills": "、".join(add_skills) if add_skills else "无",
|
"job_title": job_title, "add_skills": "、".join(add_skills) if add_skills else "无",
|
||||||
"original_summary": original_summary or "暂无",
|
"original_summary": original_summary or "暂无",
|
||||||
})
|
})
|
||||||
|
log.info(f"AI优化summary完成 ({round(time.monotonic() - t0, 2)}s)")
|
||||||
|
return result
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
log.warning(f"AI优化summary失败: {e}")
|
log.warning(f"AI优化summary失败: {e} ({round(time.monotonic() - t0, 2)}s)")
|
||||||
return original_summary
|
return original_summary
|
||||||
|
|
||||||
|
|
||||||
@@ -65,21 +69,24 @@ async def optimize_summary(job_title: str, add_skills: list[str], original_summa
|
|||||||
|
|
||||||
_experience_optimize_chain = (
|
_experience_optimize_chain = (
|
||||||
ChatPromptTemplate.from_messages([("system", EXPERIENCE_OPTIMIZE_PROMPT), ("human", "请开始优化。")])
|
ChatPromptTemplate.from_messages([("system", EXPERIENCE_OPTIMIZE_PROMPT), ("human", "请开始优化。")])
|
||||||
| LLM.JIAYU_CLAUDE_SONNET_4_5.create(temperature=0.3)
|
| LLM.DOUBAO_PRO_32K.create(temperature=0.3)
|
||||||
| StrOutputParser()
|
| StrOutputParser()
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
async def optimize_module(job_title: str, job_description: str, module_data: str) -> list | dict | None:
|
async def optimize_module(job_title: str, job_description: str, module_data: str) -> list | dict | None:
|
||||||
"""优化子表模块经历描述,返回修改后的完整模块数据"""
|
"""优化单条经历描述,返回修改后的记录数据"""
|
||||||
|
t0 = time.monotonic()
|
||||||
try:
|
try:
|
||||||
raw = await _experience_optimize_chain.ainvoke({
|
raw = await _experience_optimize_chain.ainvoke({
|
||||||
"job_title": job_title, "job_description": job_description or "",
|
"job_title": job_title, "job_description": job_description or "",
|
||||||
"original_module_data": module_data,
|
"original_module_data": module_data,
|
||||||
})
|
})
|
||||||
return parse_llm_json(raw)
|
result = parse_llm_json(raw)
|
||||||
|
log.info(f"AI优化经历模块完成 ({round(time.monotonic() - t0, 2)}s)")
|
||||||
|
return result
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
log.warning(f"AI优化经历模块失败: {e}")
|
log.warning(f"AI优化经历模块失败: {e} ({round(time.monotonic() - t0, 2)}s)")
|
||||||
return None
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -36,13 +36,13 @@ SUMMARY_OPTIMIZE_PROMPT = """你是一个简历优化助手。根据目标岗位
|
|||||||
4. 避免过度优化,改动越少越好
|
4. 避免过度优化,改动越少越好
|
||||||
5. 直接输出优化后的文本,不要其他内容"""
|
5. 直接输出优化后的文本,不要其他内容"""
|
||||||
|
|
||||||
EXPERIENCE_OPTIMIZE_PROMPT = """你是一个简历优化助手。根据目标岗位信息,微调用户的经历描述。
|
EXPERIENCE_OPTIMIZE_PROMPT = """你是一个简历优化助手。根据目标岗位信息,微调用户的一条经历描述。
|
||||||
|
|
||||||
【目标岗位】
|
【目标岗位】
|
||||||
{job_title}
|
{job_title}
|
||||||
{job_description}
|
{job_description}
|
||||||
|
|
||||||
【原始经历数据】
|
【原始经历数据(单条记录)】
|
||||||
{original_module_data}
|
{original_module_data}
|
||||||
|
|
||||||
规则:
|
规则:
|
||||||
@@ -50,7 +50,7 @@ EXPERIENCE_OPTIMIZE_PROMPT = """你是一个简历优化助手。根据目标岗
|
|||||||
2. 让描述更贴合目标岗位方向,但不要编造内容
|
2. 让描述更贴合目标岗位方向,但不要编造内容
|
||||||
3. 避免过度优化,改动越少越好
|
3. 避免过度优化,改动越少越好
|
||||||
4. description 字段是 [{{"id": "xxx", "text": "xxx"}}] 格式:修改时保留原 id 只改 text,新增段落生成随机8位字符串作为 id,删除段落直接移除
|
4. description 字段是 [{{"id": "xxx", "text": "xxx"}}] 格式:修改时保留原 id 只改 text,新增段落生成随机8位字符串作为 id,删除段落直接移除
|
||||||
5. 返回修改后的完整模块数据(JSON 格式,与输入格式一致)"""
|
5. 返回修改后的单条记录(JSON 对象格式,与输入格式一致,不要包裹在数组中)"""
|
||||||
|
|
||||||
AGENT_PLAN_PROMPT = """你是一个简历编辑助手。你的唯一职责是根据用户指令修改简历内容。
|
AGENT_PLAN_PROMPT = """你是一个简历编辑助手。你的唯一职责是根据用户指令修改简历内容。
|
||||||
|
|
||||||
|
|||||||
@@ -8,6 +8,7 @@
|
|||||||
|
|
||||||
import asyncio
|
import asyncio
|
||||||
import json
|
import json
|
||||||
|
import time
|
||||||
|
|
||||||
from sqlalchemy import select
|
from sqlalchemy import select
|
||||||
from sqlalchemy.ext.asyncio import AsyncSession
|
from sqlalchemy.ext.asyncio import AsyncSession
|
||||||
@@ -97,7 +98,7 @@ class SkillGapService:
|
|||||||
|
|
||||||
async def generate_customize_resume(self, user_id: int, job_id: int, resume_id: int,
|
async def generate_customize_resume(self, user_id: int, job_id: int, resume_id: int,
|
||||||
optimize_modules: list[str], add_skills: list[str]) -> None:
|
optimize_modules: list[str], add_skills: list[str]) -> None:
|
||||||
"""生成定制简历:查数据 → 并发AI优化 → 存Redis"""
|
"""生成定制简历:查数据 → 按单条记录并发AI优化 → 存数据库"""
|
||||||
if not optimize_modules:
|
if not optimize_modules:
|
||||||
raise ValueError("请至少选择一个优化模块")
|
raise ValueError("请至少选择一个优化模块")
|
||||||
# 1. 查简历 + 岗位
|
# 1. 查简历 + 岗位
|
||||||
@@ -105,55 +106,71 @@ class SkillGapService:
|
|||||||
job = await self._get_job(job_id)
|
job = await self._get_job(job_id)
|
||||||
# 2. 组装基础定制简历
|
# 2. 组装基础定制简历
|
||||||
cr = customize_resume_store.build_from_detail(detail)
|
cr = customize_resume_store.build_from_detail(detail)
|
||||||
# 3. 并发 AI 优化
|
# 3. 构建并发任务(按单条记录粒度)
|
||||||
tasks = []
|
|
||||||
job_desc = f"{job.description or ''}\n{job.requirement or ''}"
|
job_desc = f"{job.description or ''}\n{job.requirement or ''}"
|
||||||
|
tasks: list[tuple[str, int, object]] = []
|
||||||
if "summary" in optimize_modules:
|
if "summary" in optimize_modules:
|
||||||
tasks.append(("summary", optimize_summary(job.title or "", add_skills, detail.resume.summary or "")))
|
tasks.append(("summary", 0, optimize_summary(job.title or "", add_skills, detail.resume.summary or "")))
|
||||||
if "experience" in optimize_modules:
|
if "experience" in optimize_modules:
|
||||||
for module_name, rows_json in self._experience_tasks(cr, job.title or "", job_desc):
|
for mod_name, idx, record_json in self._experience_tasks(cr):
|
||||||
tasks.append((module_name, optimize_module(job.title or "", job_desc, rows_json)))
|
tasks.append((mod_name, idx, optimize_module(job.title or "", job_desc, record_json)))
|
||||||
# 执行并发
|
log.info(f"定制简历优化开始: {len(tasks)}个并发任务 [modules={optimize_modules}, job={job_id}, resume={resume_id}]")
|
||||||
|
# 4. 并发执行
|
||||||
if tasks:
|
if tasks:
|
||||||
keys = [t[0] for t in tasks]
|
t0 = time.monotonic()
|
||||||
results = await asyncio.gather(*[t[1] for t in tasks], return_exceptions=True)
|
results = await asyncio.gather(*[t[2] for t in tasks], return_exceptions=True)
|
||||||
for key, result in zip(keys, results):
|
log.info(f"定制简历优化全部完成, 总耗时={round(time.monotonic() - t0, 2)}s")
|
||||||
if isinstance(result, Exception):
|
for (mod_name, idx, _), result in zip(tasks, results):
|
||||||
log.warning(f"定制简历优化[{key}]失败: {result}")
|
if isinstance(result, Exception) or result is None:
|
||||||
continue
|
continue
|
||||||
self._apply_optimize_result(cr, key, result)
|
self._apply_optimize_result(cr, mod_name, idx, result)
|
||||||
# 4. skills 追加(纯内存操作)
|
# 5. skills 追加
|
||||||
if "skills" in optimize_modules and add_skills:
|
if "skills" in optimize_modules and add_skills:
|
||||||
existing = set(cr.resume.skills)
|
existing = set(cr.resume.skills)
|
||||||
cr.resume.skills.extend([s for s in add_skills if s not in existing])
|
new_skills = [s for s in add_skills if s not in existing]
|
||||||
# 5. 存数据库
|
cr.resume.skills.extend(new_skills)
|
||||||
|
if new_skills:
|
||||||
|
log.info(f"定制简历追加技能: {new_skills}")
|
||||||
|
# 6. 存数据库
|
||||||
await customize_resume_store.save(user_id, job_id, cr)
|
await customize_resume_store.save(user_id, job_id, cr)
|
||||||
|
log.info(f"定制简历已保存 [user={user_id}, job={job_id}]")
|
||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
def _experience_tasks(cr: CustomizeResume, job_title: str, job_desc: str) -> list[tuple[str, str]]:
|
def _experience_tasks(cr: CustomizeResume) -> list[tuple[str, int, str]]:
|
||||||
"""构建各子表的 AI 优化任务列表"""
|
"""构建各子表的 AI 优化任务列表,按单条记录拆分"""
|
||||||
result = []
|
result: list[tuple[str, int, str]] = []
|
||||||
for name, items in [("education", cr.education), ("work", cr.work), ("internship", cr.internship),
|
for name, items in [("education", cr.education), ("work", cr.work), ("internship", cr.internship),
|
||||||
("project", cr.project), ("competition", cr.competition)]:
|
("project", cr.project), ("competition", cr.competition)]:
|
||||||
if items:
|
for idx, item in enumerate(items or []):
|
||||||
result.append((name, json.dumps([item.model_dump(by_alias=True) for item in items], ensure_ascii=False)))
|
result.append((name, idx, json.dumps(item.model_dump(by_alias=True), ensure_ascii=False)))
|
||||||
return result
|
return result
|
||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
def _apply_optimize_result(cr: CustomizeResume, key: str, result) -> None:
|
def _apply_optimize_result(cr: CustomizeResume, key: str, idx: int, result) -> None:
|
||||||
"""将 AI 优化结果应用到定制简历"""
|
"""将 AI 优化结果应用到定制简历(单条记录粒度)"""
|
||||||
if key == "summary" and isinstance(result, str):
|
if key == "summary" and isinstance(result, str):
|
||||||
cr.resume.summary = result
|
cr.resume.summary = result
|
||||||
elif key == "education" and isinstance(result, list):
|
return
|
||||||
cr.education = [Education.model_validate(item) for item in result]
|
model_map = {"education": Education, "work": Work, "internship": Internship, "project": Project, "competition": Competition}
|
||||||
elif key == "work" and isinstance(result, list):
|
list_map = {"education": cr.education, "work": cr.work, "internship": cr.internship, "project": cr.project, "competition": cr.competition}
|
||||||
cr.work = [Work.model_validate(item) for item in result]
|
model_cls = model_map.get(key)
|
||||||
elif key == "internship" and isinstance(result, list):
|
items = list_map.get(key)
|
||||||
cr.internship = [Internship.model_validate(item) for item in result]
|
if model_cls is None or items is None:
|
||||||
elif key == "project" and isinstance(result, list):
|
log.warning(f"未知优化模块: {key}")
|
||||||
cr.project = [Project.model_validate(item) for item in result]
|
return
|
||||||
elif key == "competition" and isinstance(result, list):
|
if isinstance(result, dict):
|
||||||
cr.competition = [Competition.model_validate(item) for item in result]
|
try:
|
||||||
|
items[idx] = model_cls.model_validate(result)
|
||||||
|
except (IndexError, Exception) as e:
|
||||||
|
log.warning(f"应用优化结果[{key}[{idx}]]失败: {e}")
|
||||||
|
elif isinstance(result, list) and len(result) == 1 and isinstance(result[0], dict):
|
||||||
|
# 兼容 LLM 偶尔返回单元素数组的情况
|
||||||
|
try:
|
||||||
|
items[idx] = model_cls.model_validate(result[0])
|
||||||
|
except (IndexError, Exception) as e:
|
||||||
|
log.warning(f"应用优化结果[{key}[{idx}]]失败(数组兼容): {e}")
|
||||||
|
else:
|
||||||
|
log.warning(f"优化结果格式异常[{key}[{idx}]]: type={type(result).__name__}")
|
||||||
|
|
||||||
# ===== AI 对话编辑 =====
|
# ===== AI 对话编辑 =====
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user