mirror of
https://github.com/fastapiadmin/FastapiAdmin.git
synced 2026-09-21 04:46:26 +00:00
- 确保智能对话流式响应返回字节串,防止类型错误 - 在流式响应异常时返回友好错误信息,避免连接中断 - WebSocket聊天控制器中添加异常处理,保证异常信息反馈客户端 - WebSocket连接异常后使用finally确保连接正确关闭 refactor(resource): 统一资源接口返回HTTP URL路径 - 资源控制器新增Request参数,传递base_url实现URL转换 - 资源服务中所有路径替换为返回基于base_url的HTTP URL路径 - 文件信息、目录列表、文件上传下载接口均返回HTTP URL,提升前端友好度 - 移除递归参数及相关逻辑,简化目录统计实现 fix(database): 简化数据库依赖生成器,避免不必要的事务开启 - dependencies中db_getter取消多余事务管理,仅yield数据库会话 style(router_class): 优化操作日志路由异常处理,去除多余事务 - 简化操作日志写入流程,移除嵌套事务开启,提升代码可读性 refactor(initialize): 优化数据库初始化逻辑并增强日志与事务管理 - 初始化数据插入前打印日志,插入后标记是否需要提交事务 - PostgreSQL序列更新拆分成单独方法,针对有id字段的表执行 - 增加完整的异常捕获和回滚,保证初始化失败时事务回滚 - 读取初始化数据文件时增加日志及异常处理 fix(ai_client): 修正AI客户端HTTP连接管理及异常处理 - 使用自定义httpx AsyncClient替代默认客户端,确保连接配置 - 增加关闭客户端连接方法,避免资源泄露 - 流式响应时检查选择器内容有效性,提升稳定性 chore(cleanup): 移除MySQL快照SQL文件,保持仓库整洁 - 删除无用的SQL数据转储文件,减小仓库体积并维护清洁度
57 lines
1.9 KiB
Python
57 lines
1.9 KiB
Python
# -*- coding: utf-8 -*-
|
|
|
|
from openai import AsyncOpenAI, OpenAI
|
|
from openai.types.chat.chat_completion import ChatCompletion
|
|
import httpx
|
|
|
|
from app.config.setting import settings
|
|
from app.core.logger import logger
|
|
|
|
|
|
class AIClient:
|
|
|
|
def __init__(self):
|
|
self.model = settings.QWEN_MODEL
|
|
# 创建一个不带冲突参数的httpx客户端
|
|
self.http_client = httpx.AsyncClient(
|
|
timeout=30.0,
|
|
follow_redirects=True
|
|
)
|
|
|
|
# 使用自定义的http客户端
|
|
self.client = AsyncOpenAI(
|
|
api_key=settings.QWEN_API_KEY,
|
|
base_url=settings.QWEN_BASE_URL,
|
|
http_client=self.http_client
|
|
)
|
|
|
|
async def process(self, query: str):
|
|
"""处理查询并返回流式响应"""
|
|
system_prompt = """你是一个有用的AI助手,可以帮助用户回答问题和提供帮助。请用中文回答用户的问题。"""
|
|
|
|
try:
|
|
# 使用 await 调用异步客户端
|
|
response = await self.client.chat.completions.create(
|
|
model=self.model,
|
|
messages=[
|
|
{"role": "system", "content": system_prompt},
|
|
{"role": "user", "content": query}
|
|
],
|
|
stream=True
|
|
)
|
|
|
|
# 流式返回响应
|
|
async for chunk in response:
|
|
if chunk.choices and chunk.choices[0].delta.content:
|
|
yield chunk.choices[0].delta.content
|
|
|
|
except Exception as e:
|
|
logger.error(f"AI处理查询失败: {str(e)}")
|
|
yield f"抱歉,处理您的请求时出现了错误: {str(e)}"
|
|
|
|
async def close(self):
|
|
"""关闭客户端连接"""
|
|
if hasattr(self, 'client'):
|
|
await self.client.close()
|
|
if hasattr(self, 'http_client'):
|
|
await self.http_client.aclose() |