#day21 智能简报API import os import re import json from datetime import datetime from dotenv import load_dotenv from fastapi import FastAPI, HTTPException from pydantic import BaseModel from langchain_openai import ChatOpenAI from langchain_community.tools.tavily_search import TavilySearchResults # 加载环境变量 load_dotenv() # ----- 1. 初始化 FastAPI 应用 ----- app = FastAPI( title="智能简报生成器 API", description="根据主题,自动生成带摘要和配图的智能简报", version="2.0.0" ) # ----- 2. 定义请求和响应的数据模型 (Pydantic) ----- class BriefingRequest(BaseModel): topic: str = "AI应用开发工程师" # 默认值,方便测试 max_results: int = 5 # 可选:控制搜索条数 class BriefingResponse(BaseModel): status: str filename: str summary_preview: str total_words: int generated_at: str # ----- 3. 初始化 LLM 和搜索工具 ----- llm = ChatOpenAI( model="deepseek-chat", api_key=os.getenv("DEEPSEEK_API_KEY"), base_url="https://api.deepseek.com", temperature=0.3 ) search_tool = TavilySearchResults( api_key=os.getenv("TAVILY_API_KEY"), max_results=5, include_answer=True ) # ----- 4. 核心业务函数 (从你上周的代码中移植) ----- def search_news(topic: str) -> list: """搜索最新资讯""" try: raw = search_tool.invoke({"query": topic}) results = [] for item in raw: results.append({ "title": item.get("title", "无标题"), "content": item.get("content", item.get("snippet", "无摘要"))[:500], "url": item.get("url", "#") }) return results except Exception as e: return [{"title": "搜索失败", "content": str(e), "url": "#"}] def summarize_news(topic: str, search_results: list) -> str: """生成摘要""" formatted = "" for i, item in enumerate(search_results[:5], 1): formatted += f"\n**来源 {i}:{item['title']}**\n{item['content']}\n" prompt = f""" 你是一位专业的信息分析师。根据以下关于 "{topic}" 的搜索结果,生成一份简洁、清晰的摘要。 要求:300-500字,提炼 3-5 个核心观点,分点列出。 搜索结果:{formatted} 请直接输出摘要正文。 """ response = llm.invoke(prompt) return response.content def generate_briefing(topic: str, summary: str, image_path: str, search_results: list) -> str: """生成 Markdown 简报文件""" safe_topic = re.sub(r'[\\/*?:"<>|]', "_", topic) timestamp = datetime.now().strftime("%Y%m%d_%H%M%S") filename = f"简报_{safe_topic}_{timestamp}.md" news_section = "" for i, item in enumerate(search_results[:5], 1): news_section += f"\n### {i}. [{item['title']}]({item['url']})\n\n{item['content']}\n" content = f"""# 📰 智能简报:{topic} > **生成时间**:{datetime.now().strftime("%Y-%m-%d %H:%M:%S")} > **数据来源**:Tavily 搜索引擎 ## 📌 摘要 {summary} ## 🔗 最新资讯 {news_section} ## 🎨 配图 ![配图]({image_path}) --- *本简报由 AI 自动生成* """ with open(filename, "w", encoding="utf-8") as f: f.write(content) return filename # ----- 5. 核心 API 端点 ----- @app.post("/generate-briefing", response_model=BriefingResponse) async def generate_briefing_endpoint(request: BriefingRequest): """ 接收一个主题 (topic),生成一份完整的智能简报。 返回:状态、文件名、摘要预览、字数、生成时间。 """ try: topic = request.topic.strip() if not topic: raise HTTPException(status_code=400, detail="主题不能为空") # 1. 搜索 search_results = search_news(topic) # 2. 生成摘要 summary = summarize_news(topic, search_results) # 3. 图像生成(API 版本简化,使用占位图) image_path = "https://via.placeholder.com/800x400?text=AI+Generated+Image" # 4. 生成简报文件 filename = generate_briefing(topic, summary, image_path, search_results) return BriefingResponse( status="success", filename=filename, summary_preview=summary[:150] + ("..." if len(summary) > 150 else ""), total_words=len(summary), generated_at=datetime.now().isoformat() ) except Exception as e: raise HTTPException(status_code=500, detail=str(e)) # ----- 6. 健康检查(用于验证服务是否运行)----- @app.get("/health") async def health_check(): return {"status": "ok", "service": "智能简报生成器", "version": "2.0.0"} # ----- 7. 根路径提示 ----- @app.get("/") async def root(): return { "message": "欢迎使用智能简报生成器 API!", "docs": "/docs", "endpoints": { "POST /generate-briefing": "生成简报", "GET /health": "健康检查" } }