japi/apps/jchat/api.py
2025-05-12 02:39:56 +08:00

60 lines
2.1 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

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))