File size: 8,540 Bytes
64ed020 ff58f93 64ed020 66c4662 64ed020 66c4662 64ed020 66c4662 64ed020 66c4662 64ed020 66c4662 64ed020 66c4662 64ed020 66c4662 64ed020 66c4662 64ed020 66c4662 64ed020 ff58f93 64ed020 27f2594 64ed020 27f2594 64ed020 27f2594 64ed020 27f2594 5a49fb1 64ed020 27f2594 64ed020 ff58f93 27f2594 64ed020 ff58f93 64ed020 27f2594 64ed020 27f2594 ff58f93 64ed020 27f2594 64ed020 66c4662 ff58f93 64ed020 66c4662 64ed020 ff58f93 64ed020 66c4662 64ed020 66c4662 64ed020 66c4662 64ed020 66c4662 64ed020 27f2594 64ed020 ff58f93 64ed020 66c4662 64ed020 66c4662 64ed020 66c4662 64ed020 66c4662 64ed020 66c4662 64ed020 66c4662 64ed020 66c4662 |
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 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 |
import os
import time
import json
import asyncio
from typing import List, Optional, Dict, Any, Union, Literal
from pydantic import BaseModel, Field
from fastapi import FastAPI, HTTPException, Request, Response
from fastapi.middleware.cors import CORSMiddleware
from sse_starlette.sse import EventSourceResponse
from duckai import DuckAI
# Danh sách các model được hỗ trợ
SUPPORTED_MODELS = [
"gpt-4o-mini",
"llama-3.3-70b",
"claude-3-haiku",
"o3-mini",
"mistral-small-3"
]
app = FastAPI(title="DuckAI OpenAI Adapter API")
# Thêm CORS middleware
app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
# Models cho OpenAI API format
class Message(BaseModel):
role: Literal["system", "user", "assistant"]
content: str
class ChatCompletionRequest(BaseModel):
model: str
messages: List[Message]
temperature: Optional[float] = 1.0
max_tokens: Optional[int] = None
stream: Optional[bool] = False
class ChatCompletionResponse(BaseModel):
id: str = Field(default_factory=lambda: f"chatcmpl-{os.urandom(12).hex()}")
object: str = "chat.completion"
created: int = Field(default_factory=lambda: int(time.time()))
model: str
choices: List[Dict[str, Any]]
usage: Dict[str, int]
def format_chat_history(messages: List[Message]) -> str:
"""
Chuyển đổi danh sách tin nhắn từ định dạng OpenAI sang định dạng
mà DuckAI có thể xử lý (string với các dòng "user: " và "assistant: ")
"""
formatted_history = ""
for message in messages:
if message.role == "system":
# Xử lý tin nhắn system như một tin nhắn user đặc biệt
formatted_history += f"user: [SYSTEM] {message.content}\n"
else:
formatted_history += f"{message.role}: {message.content}\n"
return formatted_history.strip()
async def stream_response_character_by_character(content: str, request: Request, response_id: str, model: str):
"""
Generator để stream phản hồi theo từng ký tự với tốc độ phù hợp
"""
if await request.is_disconnected():
return
# Gửi tin nhắn đầu tiên với role và content rỗng
data = {
"id": response_id,
"object": "chat.completion.chunk",
"created": int(time.time()),
"model": model,
"choices": [
{
"index": 0,
"delta": {
"role": "assistant",
},
"finish_reason": None
}
]
}
yield json.dumps(data)
await asyncio.sleep(0.001) # Đợi một chút trước khi bắt đầu nội dung
# Stream nội dung theo từng ký tự
buffer = ""
for char in content:
if await request.is_disconnected():
break
buffer += char
# Tích lũy ký tự trong buffer và gửi theo các đơn vị có ý nghĩa
# (giúp tránh gửi quá nhiều sự kiện nhỏ và đảm bảo hiển thị tốt hơn)
if len(buffer) >= 3 or char in [' ', '\n', '.', '!', '?', ',']:
data = {
"id": response_id,
"object": "chat.completion.chunk",
"created": int(time.time()),
"model": model,
"choices": [
{
"index": 0,
"delta": {
"content": buffer
},
"finish_reason": None
}
]
}
yield json.dumps(data)
buffer = ""
# Điều chỉnh thời gian delay để có tốc độ stream hợp lý
# Ký tự xuống dòng sẽ có thời gian delay lâu hơn một chút
delay = 0.05 if char == '\n' else 0.01
await asyncio.sleep(delay)
# Gửi nốt buffer nếu còn
if buffer:
data = {
"id": response_id,
"object": "chat.completion.chunk",
"created": int(time.time()),
"model": model,
"choices": [
{
"index": 0,
"delta": {
"content": buffer
},
"finish_reason": None
}
]
}
yield json.dumps(data)
# Gửi message cuối cùng để đánh dấu kết thúc
data = {
"id": response_id,
"object": "chat.completion.chunk",
"created": int(time.time()),
"model": model,
"choices": [
{
"index": 0,
"delta": {},
"finish_reason": "stop"
}
]
}
yield json.dumps(data)
# Thêm [DONE] để đánh dấu kết thúc stream (theo chuẩn OpenAI)
yield "[DONE]"
@app.post("/v1/chat/completions")
async def create_chat_completion(request: Request, response: Response):
"""
Endpoint tạo chat completion với khả năng streaming
"""
try:
# Đọc request body
body = await request.json()
# Tạo request object từ body
completion_request = ChatCompletionRequest(**body)
# Kiểm tra model
if completion_request.model not in SUPPORTED_MODELS:
supported_models_str = ", ".join(SUPPORTED_MODELS)
raise HTTPException(
status_code=400,
detail=f"Model '{completion_request.model}' không được hỗ trợ. Các models được hỗ trợ: {supported_models_str}"
)
# Chuyển đổi danh sách tin nhắn sang định dạng DuckAI
chat_history = format_chat_history(completion_request.messages)
# Tạo ID phản hồi
response_id = f"chatcmpl-{os.urandom(12).hex()}"
# Gọi DuckAI API (không hỗ trợ streaming nên chúng ta sẽ lấy toàn bộ phản hồi)
duck_response = DuckAI().chat(chat_history, model=completion_request.model)
duck_response = duck_response.strip()
# Nếu request yêu cầu streaming
if completion_request.stream:
return EventSourceResponse(
stream_response_character_by_character(
duck_response,
request,
response_id,
completion_request.model
),
media_type="text/event-stream"
)
# Trả về phản hồi thông thường (không streaming)
response_data = {
"id": response_id,
"object": "chat.completion",
"created": int(time.time()),
"model": completion_request.model,
"choices": [
{
"index": 0,
"message": {
"role": "assistant",
"content": duck_response
},
"finish_reason": "stop"
}
],
"usage": {
"prompt_tokens": len(chat_history) // 4, # Ước tính đơn giản
"completion_tokens": len(duck_response) // 4,
"total_tokens": (len(chat_history) + len(duck_response)) // 4
}
}
return response_data
except Exception as e:
raise HTTPException(status_code=500, detail=f"Error: {str(e)}")
@app.get("/v1/models")
async def list_models():
"""Endpoint để liệt kê các model được hỗ trợ"""
models_data = []
for model_id in SUPPORTED_MODELS:
models_data.append({
"id": model_id,
"object": "model",
"created": int(time.time()),
"owned_by": "duckai"
})
return {
"object": "list",
"data": models_data
}
@app.get("/")
async def root():
return {
"message": "DuckAI OpenAI Adapter API is running. Send requests to /v1/chat/completions",
"supported_models": SUPPORTED_MODELS
}
if __name__ == "__main__":
import uvicorn
# Cấu hình port và host cho Hugging Face Spaces
uvicorn.run("main:app", host="0.0.0.0", port=7860, reload=True) |