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


相关推荐
江畔柳前堤3 小时前
roLabelImg 详细安装教程
开发语言·人工智能·后端·云原生
阿里云大数据AI技术3 小时前
分链路差异化设计的DSP准实时数仓|钛动科技基于阿里云实时计算 Flink 版 + DLF Paimon + EMR Serverless StarRocks 的实践
人工智能·flink
陕西企来客3 小时前
2026年7月AI智能搜索曝光趋势研判
大数据·人工智能·机器学习·ai智能搜索曝光
阿里云大数据AI技术4 小时前
从算力到智能体,面向 Agentic AI 的基础设施演进
人工智能·agent
hangyuekejiGEO4 小时前
GEO技术服务选型指南
大数据·人工智能·python
阿里云大数据AI技术5 小时前
EMR Serverless Spark AI Function 的双维降本实践
人工智能·sql·spark
维基框架5 小时前
GitHub源码处理提速 一趟扫描反而更慢
人工智能·github
冬奇Lab5 小时前
代码库知识库系列(05):向量检索 vs 知识图谱——加了调用图并没有变更好
人工智能
AKAMAI5 小时前
你的源服务器可能是你做出的最昂贵决定
运维·人工智能·云计算
冬奇Lab5 小时前
【无标题】
人工智能·开源