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 调试。

相关推荐
打妖妖灵滴哪吒7 小时前
github创建远程仓库+推送代码(图文版)
github
笨鸟先飞,勤能补拙8 小时前
AI 赋能网络安全:技术全景、成熟度评估与实战案例
人工智能·python·安全·web安全·网络安全·sqlite·github
笨鸟先飞,勤能补拙10 小时前
AI 赋能网络安全领域深度剖析
网络·人工智能·windows·安全·web安全·网络安全·github
天使day13 小时前
FastAPI快速入门
python·fastapi
gwf21613 小时前
SSD读写速度深度解析:顺序读写vs随机读写、IOPS、延迟,你的硬盘性能到底怎么看?
git·嵌入式硬件·缓存·github·智能硬件
笨鸟先飞,勤能补拙19 小时前
下一个十年:网络安全正在被重写
网络·人工智能·安全·web安全·网络安全·github
潘正翔19 小时前
k8s进阶_Harbor镜像仓库
git·云原生·容器·kubernetes·gitee·github
vibecoding7719 小时前
GitHub 2026 年 7 月热榜:累计 Star 总榜与月度飙星榜
人工智能·github·ai编程
Pniubi20 小时前
Gitee&GitHub同步仓库教程
gitee·github
TunerT_TQ20 小时前
GitHub深度工程评测:AI 系统提示词泄露知识库深度评测:6万星system_prompts_leaks情报资产背后,藏着什么?
人工智能·chatgpt·github·提示词工程·#valhalla静态工程审阅·systemprompt·大模型工程