← 返回首页
🧠

报告生成:AI自动生成报告

📂 llm ⏱ 3 min 408 words

--- title: "报告生成:AI自动生成报告" description: "使用LLM自动生成各种类型的报告" tags: ["报告生成", "自动报告", "AI写作", "LLM", "文档"] category: "llm" icon: "📄"

报告生成:AI自动生成报告

报告生成概述

LLM报告生成是利用AI技术自动生成各种类型报告的技术,包括数据分析报告、商业报告、技术报告等。

核心功能

1. 报告生成器

from openai import OpenAI
from typing import Dict, List
from dataclasses import dataclass
from datetime import datetime

@dataclass
class ReportConfig:
    """报告配置"""
    title: str
    report_type: str
    audience: str
    sections: List[str]
    data_source: Dict = None

class ReportGenerator:
    """报告生成器"""
    
    def __init__(self, model: str = "gpt-4"):
        self.client = OpenAI()
        self.model = model
    
    def generate_report(self, config: ReportConfig) -> str:
        """生成报告"""
        prompt = self._build_prompt(config)
        
        response = self.client.chat.completions.create(
            model=self.model,
            messages=[
                {"role": "system", "content": "你是一个专业的报告撰写专家。"},
                {"role": "user", "content": prompt}
            ],
            temperature=0.4
        )
        
        return response.choices[0].message.content
    
    def _build_prompt(self, config: ReportConfig) -> str:
        """构建提示"""
        prompt = f"""请生成一份{config.report_type}报告。

标题:{config.title}
目标受众:{config.audience}
报告日期:{datetime.now().strftime('%Y-%m-%d')}

报告结构:
"""
        
        for i, section in enumerate(config.sections, 1):
            prompt += f"{i}. {section}\n"
        
        if config.data_source:
            prompt += f"\n数据来源:\n{config.data_source}\n"
        
        prompt += "\n请生成完整的报告内容。"
        
        return prompt
    
    def generate_section(self, section_name: str, context: str) -> str:
        """生成报告章节"""
        prompt = f"""请为以下报告章节生成内容:

章节名称:{section_name}
上下文信息:{context}

请生成详细的章节内容。"""
        
        response = self.client.chat.completions.create(
            model=self.model,
            messages=[
                {"role": "system", "content": "你是一个报告撰写专家。"},
                {"role": "user", "content": prompt}
            ],
            temperature=0.4
        )
        
        return response.choices[0].message.content

2. 报告模板

class ReportTemplates:
    """报告模板"""
    
    TEMPLATES = {
        "data_analysis": {
            "name": "数据分析报告",
            "sections": [
                "执行摘要",
                "数据概览",
                "分析方法",
                "关键发现",
                "详细分析",
                "结论和建议",
                "附录"
            ]
        },
        "business": {
            "name": "商业报告",
            "sections": [
                "执行摘要",
                "公司概况",
                "市场分析",
                "财务状况",
                "运营分析",
                "风险评估",
                "未来展望",
                "建议"
            ]
        },
        "technical": {
            "name": "技术报告",
            "sections": [
                "摘要",
                "引言",
                "技术背景",
                "方法论",
                "实验结果",
                "讨论",
                "结论",
                "参考文献"
            ]
        },
        "project_status": {
            "name": "项目状态报告",
            "sections": [
                "项目概述",
                "本周进展",
                "里程碑状态",
                "风险和问题",
                "下周计划",
                "资源需求"
            ]
        }
    }
    
    @staticmethod
    def get_template(report_type: str) -> Dict:
        """获取模板"""
        return ReportTemplates.TEMPLATES.get(report_type, {})
    
    @staticmethod
    def list_templates() -> List[str]:
        """列出模板"""
        return list(ReportTemplates.TEMPLATES.keys())

3. 报告格式化

class ReportFormatter:
    """报告格式化器"""
    
    @staticmethod
    def to_markdown(report: str, title: str) -> str:
        """转换为Markdown"""
        return f"""# {title}

{report}

---
生成时间:{datetime.now().strftime('%Y-%m-%d %H:%M:%S')}
"""
    
    @staticmethod
    def to_html(report: str, title: str) -> str:
        """转换为HTML"""
        return f"""<!DOCTYPE html>
<html>
<head>
    <title>{title}</title>
    <style>
        body {{ font-family: Arial, sans-serif; margin: 40px; }}
        h1 {{ color: #333; }}
        h2 {{ color: #666; border-bottom: 1px solid #ddd; padding-bottom: 5px; }}
        .metadata {{ color: #999; font-size: 0.9em; }}
    </style>
</head>
<body>
    <h1>{title}</h1>
    <div class="metadata">生成时间:{datetime.now().strftime('%Y-%m-%d %H:%M:%S')}</div>
    <hr>
    {report}
</body>
</html>
"""
    
    @staticmethod
    def add_table_of_contents(report: str) -> str:
        """添加目录"""
        import re
        
        # 提取标题
        headings = re.findall(r'^(#{1,3})\s+(.+)$', report, re.MULTILINE)
        
        toc = "## 目录\n\n"
        for level, heading in headings:
            indent = "  " * (len(level) - 1)
            toc += f"{indent}- {heading}\n"
        
        toc += "\n---\n\n"
        
        return toc + report

使用示例

# 创建报告生成器
generator = ReportGenerator()

# 配置报告
config = ReportConfig(
    title="2024年第一季度销售分析报告",
    report_type="data_analysis",
    audience="管理层",
    sections=["执行摘要", "销售数据分析", "趋势分析", "建议"],
    data_source={
        "总销售额": "1,000,000元",
        "同比增长": "15%",
        "最畅销产品": "产品A"
    }
)

# 生成报告
report = generator.generate_report(config)

# 格式化报告
formatted_report = ReportFormatter.to_markdown(report, config.title)

# 添加目录
final_report = ReportFormatter.add_table_of_contents(formatted_report)

print(final_report)

最佳实践

  1. 明确受众:根据受众调整报告风格
  2. 结构清晰:使用清晰的报告结构
  3. 数据支撑:用数据支撑观点
  4. 可视化:添加适当的图表

总结

LLM报告生成是提高报告撰写效率的强大工具。通过自动化报告生成,可以快速创建高质量的报告。