60 lines
2.1 KiB
Python
60 lines
2.1 KiB
Python
from fastapi import APIRouter, HTTPException, Request
|
||
from service import ChatService
|
||
from utils import jingrow_api_verify_and_billing
|
||
from settings import settings
|
||
import json
|
||
from functools import wraps
|
||
|
||
router = APIRouter(prefix=settings.router_prefix)
|
||
service = ChatService()
|
||
|
||
def dynamic_billing_wrapper(func):
|
||
"""动态API扣费装饰器,使用模型名称作为API名称"""
|
||
@wraps(func)
|
||
async def wrapper(data: dict, request: Request):
|
||
api_name = settings.default_api_name # 使用settings中的默认API名称
|
||
if "model" in data:
|
||
api_name = data["model"]
|
||
|
||
dynamic_decorator = jingrow_api_verify_and_billing(api_name=api_name)
|
||
decorated_func = dynamic_decorator(func)
|
||
return await decorated_func(**{"data": data, "request": request})
|
||
|
||
return wrapper
|
||
|
||
@router.post(settings.chat_route)
|
||
@dynamic_billing_wrapper
|
||
async def chat_api(data: dict, request: Request):
|
||
"""
|
||
通用文本聊天API,支持OpenAI和豆包等模型的请求格式
|
||
|
||
Args:
|
||
data: 包含以下字段的字典:
|
||
- messages: 消息列表,每个消息包含 role 和 content(必需)
|
||
- model: 选择使用的模型(可选,默认为配置的默认模型)
|
||
- temperature: 温度参数(可选,默认为0.7)
|
||
- top_p: top_p参数(可选,默认为0.9)
|
||
- max_tokens: 最大生成token数(可选,默认为2048)
|
||
request: FastAPI 请求对象
|
||
|
||
Returns:
|
||
AI生成的回复内容
|
||
"""
|
||
if "messages" not in data:
|
||
raise HTTPException(status_code=400, detail="缺少messages参数")
|
||
|
||
try:
|
||
if "model" in data:
|
||
service.model = data["model"]
|
||
if "temperature" in data:
|
||
service.temperature = data["temperature"]
|
||
if "top_p" in data:
|
||
service.top_p = data["top_p"]
|
||
if "max_tokens" in data:
|
||
service.max_tokens = data["max_tokens"]
|
||
|
||
result = await service.chat(data["messages"])
|
||
return result
|
||
except Exception as e:
|
||
raise HTTPException(status_code=500, detail=str(e))
|