Phi-3-mini-4k-instruct-gguf部署案例:Airflow中集成Phi-3-mini实现定时摘要任务

张开发
2026/4/19 6:18:46 15 分钟阅读

分享文章

Phi-3-mini-4k-instruct-gguf部署案例:Airflow中集成Phi-3-mini实现定时摘要任务
Phi-3-mini-4k-instruct-gguf部署案例Airflow中集成Phi-3-mini实现定时摘要任务1. 项目背景与需求在日常工作中我们经常需要处理大量文本信息并生成摘要。传统的人工摘要方式效率低下特别是在需要定时处理大量文档的场景下。本文将介绍如何在Airflow工作流中集成Phi-3-mini-4k-instruct-gguf模型实现自动化文本摘要任务。Phi-3-mini-4k-instruct-gguf是微软推出的轻量级文本生成模型特别适合问答、文本改写和摘要整理等场景。它的GGUF格式版本可以高效地在本地运行不需要依赖云端服务。2. 环境准备与部署2.1 基础环境要求在开始之前请确保你的系统满足以下要求Python 3.8或更高版本已安装Airflow 2.0支持CUDA的GPU推荐或性能足够的CPU至少8GB可用内存2.2 模型部署首先下载并部署Phi-3-mini-4k-instruct-gguf模型# 创建模型目录 mkdir -p ~/ai-models/microsoft cd ~/ai-models/microsoft # 下载模型文件 wget https://huggingface.co/TheBloke/Phi-3-mini-4k-instruct-gguf/resolve/main/phi-3-mini-4k-instruct.Q4_K_M.gguf # 安装llama-cpp-python pip install llama-cpp-python[server]3. 创建Airflow DAG3.1 基础DAG结构我们将创建一个名为text_summarization的DAG每天凌晨2点自动运行from datetime import datetime, timedelta from airflow import DAG from airflow.operators.python import PythonOperator default_args { owner: airflow, depends_on_past: False, start_date: datetime(2023, 1, 1), retries: 1, retry_delay: timedelta(minutes5), } dag DAG( text_summarization, default_argsdefault_args, description自动文本摘要任务, schedule_interval0 2 * * *, catchupFalse )3.2 模型调用函数创建一个Python函数来调用Phi-3-mini模型生成摘要from llama_cpp import Llama def generate_summary(text): # 初始化模型 llm Llama( model_path~/ai-models/microsoft/phi-3-mini-4k-instruct.Q4_K_M.gguf, n_ctx2048, n_threads4 ) # 构建提示词 prompt f请为以下文本生成一个简洁的摘要不超过100字\n\n{text} # 生成摘要 output llm( prompt, max_tokens128, temperature0.2, top_p0.9, echoFalse ) return output[choices][0][text].strip()4. 完整任务实现4.1 从数据库获取文本假设我们的文本存储在PostgreSQL数据库中from airflow.providers.postgres.hooks.postgres import PostgresHook def fetch_texts(**kwargs): postgres_hook PostgresHook(postgres_conn_idpostgres_default) conn postgres_hook.get_conn() cursor conn.cursor() cursor.execute(SELECT id, content FROM documents WHERE summary IS NULL LIMIT 10) texts cursor.fetchall() kwargs[ti].xcom_push(keytexts_to_summarize, valuetexts) cursor.close() conn.close()4.2 生成并存储摘要def process_summaries(**kwargs): ti kwargs[ti] texts ti.xcom_pull(task_idsfetch_texts, keytexts_to_summarize) postgres_hook PostgresHook(postgres_conn_idpostgres_default) conn postgres_hook.get_conn() cursor conn.cursor() for doc_id, content in texts: summary generate_summary(content) cursor.execute( UPDATE documents SET summary %s WHERE id %s, (summary, doc_id) ) conn.commit() cursor.close() conn.close()4.3 完整DAG定义将所有任务组合起来fetch_task PythonOperator( task_idfetch_texts, python_callablefetch_texts, provide_contextTrue, dagdag, ) summarize_task PythonOperator( task_idprocess_summaries, python_callableprocess_summaries, provide_contextTrue, dagdag, ) fetch_task summarize_task5. 性能优化与监控5.1 模型加载优化为了避免每次任务都重新加载模型我们可以使用Airflow的task.python装饰器并设置pool参数from airflow.decorators import task task.python(poolphi3_pool, pool_slots1) def generate_summary_task(text): # 使用全局变量保持模型加载状态 if llm not in globals(): globals()[llm] Llama( model_path~/ai-models/microsoft/phi-3-mini-4k-instruct.Q4_K_M.gguf, n_ctx2048, n_threads4 ) prompt f摘要任务{text} output globals()[llm](prompt, max_tokens128, temperature0.2) return output[choices][0][text].strip()5.2 监控与日志添加监控指标和日志记录from airflow.utils.log.logging_mixin import LoggingMixin def process_summaries_with_logging(**kwargs): logger LoggingMixin().log ti kwargs[ti] texts ti.xcom_pull(task_idsfetch_texts, keytexts_to_summarize) logger.info(f开始处理 {len(texts)} 个文档的摘要任务) for doc_id, content in texts: try: start_time time.time() summary generate_summary(content) duration time.time() - start_time logger.info(f文档 {doc_id} 摘要生成完成耗时 {duration:.2f} 秒) # 存储摘要... except Exception as e: logger.error(f处理文档 {doc_id} 时出错: {str(e)}) continue6. 实际应用建议6.1 参数调优经验根据实际使用经验以下参数组合效果较好摘要任务temperature0.2, max_tokens128文本改写temperature0.3, max_tokens256问答任务temperature0.1, max_tokens5126.2 错误处理策略建议在DAG中添加错误处理任务from airflow.operators.email import EmailOperator error_email EmailOperator( task_idsend_error_email, toyour_emailexample.com, subject摘要任务失败通知, html_contentp摘要任务执行失败请检查日志。/p, trigger_ruleone_failed, dagdag ) summarize_task error_email6.3 扩展应用场景这个方案可以轻松扩展到其他应用场景自动生成日报/周报摘要会议纪要自动整理用户反馈自动分类和摘要新闻文章自动摘要生成7. 总结与展望通过将Phi-3-mini-4k-instruct-gguf模型集成到Airflow工作流中我们实现了一个高效的定时文本摘要系统。这个方案具有以下优势本地化部署数据不需要离开内部环境保障隐私安全轻量高效Phi-3-mini模型资源占用小响应速度快灵活扩展可以轻松调整任务频率和处理量易于监控利用Airflow的监控和报警功能未来可以考虑以下改进方向添加多模型支持根据文本类型选择最适合的模型实现摘要质量自动评估机制增加批处理优化提高大规模文本处理效率获取更多AI镜像想探索更多AI镜像和应用场景访问 CSDN星图镜像广场提供丰富的预置镜像覆盖大模型推理、图像生成、视频生成、模型微调等多个领域支持一键部署。

更多文章