AI学习——FastAPI 接口封装

FastAPI 接口封装

前言:

  1. FastAPI 基础路由
  2. 网页总结 Agent / 文档问答 / RAG 封装成 API
  3. 自动生成接口文档
  4. 支持外部调用(前端、小程序、其他服务都能调用)

一、FastAPI 介绍

FastAPI = 最快、最简单把 Python 代码变成 API 的工具

  • 1分钟写接口
  • 自动生成可视化文档
  • 支持 POST/GET
  • 适合把 Agent、RAG、总结工具 做成接口供外部调用

链路:

把 网页总结Agent 封装成 API → 别人发 URL → 你返回结构化笔记


二、安装依赖

bash 复制代码
pip install fastapi uvicorn langchain langchain-openai beautifulsoup4

三、FastAPI 最基础接口

python 复制代码
from fastapi import FastAPI

app = FastAPI()

# 1. 最简单接口(GET)
@app.get("/")
def home():
    return {"message": "AI Agent API 服务已启动"}

# 2. 带参数接口
@app.get("/add")
def add(a: int, b: int):
    return {"result": a + b}

运行:

bash 复制代码
uvicorn main:app --reload

打开浏览器访问:


四、把 网页总结Agent 封装成 API

功能

  • 外部传入 url
  • API 内部调用 Agent
  • 返回 结构化笔记
  • 支持所有前端/后端/小程序调用

代码

python 复制代码
# main.py
from fastapi import FastAPI
from pydantic import BaseModel
from langchain_openai import ChatOpenAI
from langchain.memory import ConversationBufferMemory
from langchain.agents import AgentExecutor, create_react_agent
from langchain.tools import Tool
from langchain import hub
import requests
from bs4 import BeautifulSoup

# ==================
# 1. 初始化 FastAPI
# ==================
app = FastAPI(title="AI 网页总结 Agent API", version="1.0")

# ==================
# 2. 初始化 LLM
# ==================
llm = ChatOpenAI(
    model="gpt-3.5-turbo",
    temperature=0.1,
    api_key="你的API_KEY",
    base_url="https://api.chatanywhere.tech/v1"
)

# ==================
# 3. 记忆功能
# ==================
memory = ConversationBufferMemory(memory_key="chat_history", return_messages=True)

# ==================
# 4. 网页抓取工具
# ==================
def fetch_and_clean(url: str) -> str:
    try:
        html = requests.get(url, timeout=10).text
        soup = BeautifulSoup(html, "html.parser")
        tags = soup.find_all(["p", "h1", "h2", "h3", "h4", "li"])
        content = "\n".join(t.get_text(strip=True) for t in tags)
        return content[:12000]
    except Exception as e:
        return f"抓取失败:{str(e)}"

web_tool = Tool(
    name="WebFetcher",
    func=fetch_and_clean,
    description="输入URL获取网页正文"
)

# ==================
# 5. 结构化总结 Prompt
# ==================
prompt = hub.pull("hwchase17/react-chat")
prompt.template += """
请你总结网页内容,严格输出以下格式:

【文章主题】
【核心观点】
【重点内容】
【结构化笔记】
"""

# ==================
# 6. 创建 Agent
# ==================
agent = create_react_agent(llm, [web_tool], prompt)
agent_executor = AgentExecutor(
    agent=agent,
    tools=[web_tool],
    memory=memory,
    verbose=True
)

# ==================
# 7. 定义API接收参数格式
# ==================
class SummaryRequest(BaseModel):
    url: str  # 用户传入URL

# ==================
# 8. 【核心API接口】
# ==================
@app.post("/summarize", summary="输入网页链接,返回结构化总结")
def summarize_website(request: SummaryRequest):
    result = agent_executor.invoke({
        "input": request.url
    })
    return {
        "code": 200,
        "url": request.url,
        "summary": result["output"]
    }

# ==================
# 9. 健康检查接口
# ==================
@app.get("/")
def root():
    return {"status": "running", "agent": "网页总结AI"}

五、启动 API

bash 复制代码
uvicorn main:app --reload --host 0.0.0.0 --port 8000

六、自动生成的接口文档

打开浏览器访问:

👉 http://localhost:8000/docs

你会看到:

  • 接口列表
  • 可直接在线测试
  • 自动生成参数说明
  • 一键调用、看返回结果

这就是 FastAPI 最强的地方!


七、测试接口(3种方式)

方式1:在 /docs 里点「Try it out」直接测

输入:

json 复制代码
{
  "url": "https://baike.baidu.com/item/人工智能"
}

返回:

json 复制代码
{
  "code": 200,
  "url": "https://baike.baidu.com/item/人工智能",
  "summary": "【文章主题】...【核心观点】...【结构化笔记】..."
}

方式2:用 curl 调用

bash 复制代码
curl -X POST "http://localhost:8000/summarize" -H "Content-Type: application/json" -d '{"url":"https://baike.baidu.com/item/人工智能"}'

方式3:任何前端/小程序/后端都能调用

✅ Java

✅ Vue / React

✅ 微信小程序

✅ Python

✅ 移动端APP


相关推荐
楚国的小隐士5 小时前
在生产环境中和AI协作编程
ai·大模型·编程·软件工程·ai编程·软件架构
深小乐5 小时前
我在 Anthropic ELI5 上加了5样东西,做成了更好用的 ELI5+
人工智能
东风破_6 小时前
《LangGraph Memory:为什么 Agent 需要 Checkpointer?》
人工智能
锋行天下6 小时前
LangGraph 同级节点之间修改数据先后问题
人工智能
u1301306 小时前
AI 日报(2026年9月12日)
人工智能
东风破_6 小时前
《LangGraph Human-in-the-loop:Interrupt 如何让 Agent 等待人工确认》
人工智能
2601_962218616 小时前
万象生鲜系统业财一体化底层打通技术自动生成经营账单
大数据·数据库·人工智能·python·算法
智塑未来6 小时前
中文短剧出海翻译工具横评:VMEG AI、鬼手、Vozo AI、ElevenLabs怎么选?
人工智能
东风破_6 小时前
《LangGraph 条件路由与循环:如何让 Agent 自己决定下一步?》
人工智能
我爱吃土豆16 小时前
AI 编程工具远程开发指南:Codex 桌面版与 WorkBuddy 通过 SSH 连接云服务器实践
服务器·人工智能·ssh