FastAPI + OpenAI 模型 的 GitHub 项目结构模板

FastAPI + OpenAI 模型 的 GitHub 项目结构模板,适合用作大模型(如 GPT-4) API 服务的基础框架。该模板包括了基本的项目结构、配置、文档以及与 OpenAI API 的交互方式。

项目结构

bash 复制代码
fastapi-openai-api/
├── app/
│   ├── __init__.py                # Python 包初始化文件
│   ├── main.py                    # FastAPI 主应用文件
│   ├── models.py                  # 数据模型(请求和响应)
│   ├── openai_service.py          # OpenAI 接口交互逻辑
│   ├── config.py                  # 配置文件(API 密钥等)
│   ├── schemas.py                 # 请求和响应的 Pydantic 模型
│   ├── utils.py                   # 辅助工具函数(如日志记录等)
│   └── requirements.txt           # Python 依赖列表
├── docker/
│   ├── Dockerfile                 # Docker 构建文件
│   └── docker-compose.yml         # Docker Compose 配置(如果需要)
├── tests/
│   ├── test_main.py               # FastAPI API 测试文件
│   └── test_openai_service.py     # OpenAI 服务单元测试文件
├── .gitignore                     # Git 忽略文件
├── README.md                      # 项目说明文档
└── requirements.txt               # 项目依赖(包含 FastAPI 和 OpenAI 库)

文件说明

1.app/main.py - FastAPI 应用入口
python 复制代码
from fastapi import FastAPI, HTTPException
from app.schemas import ChatRequest, ChatResponse
from app.openai_service import ask_openai

app = FastAPI(title="FastAPI + OpenAI API")

@app.post("/chat", response_model=ChatResponse)
async def chat(req: ChatRequest):
    try:
        answer = await ask_openai(req.question)
        return ChatResponse(answer=answer)
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))
2.app/schemas.py - 请求和响应的 Pydantic 模型
python 复制代码
from pydantic import BaseModel

class ChatRequest(BaseModel):
    question: str

class ChatResponse(BaseModel):
    answer: str
3.app/openai_service.py - 与 OpenAI API 的交互
python 复制代码
import openai
from app.config import OPENAI_API_KEY

openai.api_key = OPENAI_API_KEY

async def ask_openai(question: str) -> str:
    response = openai.Completion.create(
        model="gpt-4",  # 这里可以根据需要更换为不同的模型
        prompt=question,
        max_tokens=150
    )
    return response.choices[0].text.strip()
4.app/config.py - 配置文件
python 复制代码
import os

# 推荐使用环境变量来管理敏感信息
OPENAI_API_KEY = os.getenv("OPENAI_API_KEY", "sk-xxxxxxxxxxxxxxxxxx")
5.app/requirements.txt - Python 依赖
python 复制代码
fastapi
uvicorn
openai
python-dotenv
6.tests/test_main.py - FastAPI API 测试
python 复制代码
from fastapi.testclient import TestClient
from app.main import app

client = TestClient(app)

def test_chat():
    response = client.post("/chat", json={"question": "What's the weather like?"})
    assert response.status_code == 200
    assert "answer" in response.json()
7.tests/test_openai_service.py - OpenAI 服务单元测试
python 复制代码
import pytest
from app.openai_service import ask_openai

@pytest.mark.asyncio
async def test_ask_openai():
    answer = await ask_openai("What is the capital of France?")
    assert answer == "Paris"  # 你可以根据 OpenAI 的回答调整预期结果

Docker 部署

1.docker/Dockerfile - Dockerfile
python 复制代码
# 使用官方 Python 镜像
FROM python:3.9-slim

# 设置工作目录
WORKDIR /app

# 将本地代码复制到 Docker 容器中
COPY . /app

# 安装依赖
RUN pip install --no-cache-dir -r requirements.txt

# 启动 FastAPI 服务
CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "8000"]
2.docker/docker-compose.yml - Docker Compose 配置
yaml 复制代码
version: '3.8'

services:
  fastapi-openai:
    build: .
    ports:
      - "8000:8000"
    environment:
      - OPENAI_API_KEY=${OPENAI_API_KEY}  # 从环境变量中读取 API 密钥

运行项目

1.本地运行:
bash 复制代码
uvicorn app.main:app --reload
2.Docker 构建与运行:
bash 复制代码
docker-compose up --build

访问 http://127.0.0.1:8000/docs,你将看到自动生成的 Swagger UI,支持 API 调试。

相关推荐
流量猎手16 小时前
宝塔中更新github
github
敢敢是只喵i20 小时前
n8n 接入业务系统:如何正确等待一项 Agent 任务?从稳定 request_id、job_id 到超时续查
github
wangruofeng20 小时前
新 Mac 到手先装什么:AI Builder 的 44 款工具,基础层照抄、场景层按需
github·aigc·ai编程
亖十不惑20 小时前
二、Codex Memories 源码解析:记忆的生成、整理与存储
github
面向Google编程21 小时前
GitHub 宕机近 8 小时!一次 sidecar 配置失误,如何放倒全球最大代码平台
github
峰向AI21 小时前
Modular 平台:一个人想改写 AI 开发的底层规则
github
IvanCodes1 天前
GitHub 本周热门开源项目:Agent Infra与端侧 AI|8.17–8.23
开源·github
高频因子挖掘机1 天前
量化交易系统的数据层和策略层如何解耦?从紧耦合泥潭到优雅分层架构
后端·github
刘新洲1 天前
我以为 AI Agent 只是调模型,直到我亲手补上审批、Outbox 和故障恢复
python·agent·fastapi
量化小c1 天前
从数据到策略:QuantDash + DuckDB 搭建 5 分钟 K 线本地量化数据仓库
后端·github