python+FastAPI实现兼容openai api协议的多模型统一代理oneapi代码
代码语言:python
所属分类:其他
代码描述:python+FastAPI实现兼容openai api协议的多模型统一代理oneapi代码,只要这个大模型的api兼容openai api协议,就可以直接加进来,客户端请求的时候直接将model改成模型商/模型名的形式,例如gpt4o就是openai/gpt4o,还可以对客户端进行自定义的鉴权验证。
代码标签: python FastAPI 兼容 openai api 协议 多模型 统一 代理 oneapi 代
下面为部分代码预览,完整代码请点击下载或在bfwstudio webide中打开
#!/usr/local/python3/bin/python3
# -*- coding: utf-8 -*
# main.py
import asyncio
import time
import hashlib
import json
from typing import Dict, Any, Tuple
import httpx
from fastapi import FastAPI, Request, HTTPException, Depends
from fastapi.middleware.cors import CORSMiddleware
from starlette.responses import StreamingResponse
from cachetools import TTLCache
# --- 1. 配置中心 ---
# 在这里集中管理所有后端模型的配置
# 格式: "前缀": {"api_key": "...", "base_url": "..."}
MODEL_CONFIGS: Dict[str, Dict[str, str]] = {
"openai": {
"api_key": "sk-your_openai_api_key",
"base_url": "https://api.openai.com/v1"
},
"gemini": {
"api_key": "your_google_ai_studio_api_key",
"base_url": "https://generativelanguage.googleapis.com/v1beta/openai"
},
"qwen": {
"api_key": "sk-your-qwen-key",
"base_url": "https://dashscope.aliyuncs.com/compatible-mode/v1"
},.........完整代码请登录后点击上方下载按钮下载查看















网友评论0