1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200
| from fastapi import FastAPI, HTTPException, Request from fastapi.middleware.cors import CORSMiddleware from fastapi.responses import StreamingResponse import logging import time from typing import AsyncGenerator
from models import ( ChatCompletionRequest, ChatCompletionResponse, ChatCompletionStreamResponse, StreamChoice, Delta )
app = FastAPI( title="OpenAI Compatible API", description="OpenAI 格式兼容的 API 服务", version="1.0.0" )
app.add_middleware( CORSMiddleware, allow_origins=["*"], allow_credentials=True, allow_methods=["*"], allow_headers=["*"], )
@app.get("/") async def root(): """根路径""" return { "message": "OpenAI Compatible API Server", "version": "1.0.0", "endpoints": { "chat": "/v1/chat/completions", "models": "/v1/models", "health": "/health" } }
@app.get("/health") async def health_check(): """健康检查""" return {"status": "healthy", "timestamp": int(time.time())}
@app.post("/v1/chat/completions") async def create_chat_completion(request: ChatCompletionRequest, http_request: Request): """创建聊天完成""" auth_header = http_request.headers.get("Authorization") if not auth_header or not auth_header.startswith("Bearer "): raise HTTPException( status_code=401, detail={ "error": { "message": "Invalid API key provided", "type": "invalid_request_error", "code": "invalid_api_key" } } ) api_key = auth_header[7:] try: if request.stream: return StreamingResponse( generate_stream_response(request, api_key), media_type="text/event-stream", headers={ "Cache-Control": "no-cache", "Connection": "keep-alive", "Content-Type": "text/event-stream" } ) else: response = await generate_completion(request, api_key) return response except Exception as e: raise HTTPException( status_code=500, detail={ "error": { "message": str(e), "type": "server_error", "code": "internal_error" } } )
async def generate_completion(request: ChatCompletionRequest, api_key: str) -> ChatCompletionResponse: """生成非流式完成响应""" response_id = f"chatcmpl-{int(time.time())}" return ChatCompletionResponse( id=response_id, created=int(time.time()), model=request.model, choices=[ Choice( index=0, message=Message( role="assistant", content="这是一个示例响应" ), finish_reason="stop" ) ], usage=Usage( prompt_tokens=10, completion_tokens=5, total_tokens=15 ) )
async def generate_stream_response(request: ChatCompletionRequest, api_key: str) -> AsyncGenerator[str, None]: """生成流式响应""" response_id = f"chatcmpl-{int(time.time())}" created = int(time.time()) try: content_chunks = ["这是", "一个", "流式", "响应", "示例"] for chunk in content_chunks: stream_response = ChatCompletionStreamResponse( id=response_id, created=created, model=request.model, choices=[ StreamChoice( index=0, delta=Delta(content=chunk), finish_reason=None ) ] ) yield f"data: {stream_response.model_dump_json()}\n\n" import asyncio await asyncio.sleep(0.1) final_response = ChatCompletionStreamResponse( id=response_id, created=created, model=request.model, choices=[ StreamChoice( index=0, delta=Delta(), finish_reason="stop" ) ] ) yield f"data: {final_response.model_dump_json()}\n\n" yield "data: [DONE]\n\n" except Exception as e: error_response = { "error": { "message": str(e), "type": "server_error", "code": "internal_error" } } yield f"data: {json.dumps(error_response)}\n\n" yield "data: [DONE]\n\n"
@app.get("/v1/models") async def list_models(): """获取模型列表""" return { "object": "list", "data": [ { "id": "gpt-3.5-turbo", "object": "model", "created": 1677610602, "owned_by": "openai" }, { "id": "gpt-4", "object": "model", "created": 1687882411, "owned_by": "openai" } ] }
|