首次提交by MimoCode
This commit is contained in:
@@ -0,0 +1,66 @@
|
||||
from fastapi import APIRouter, Depends, Query
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
from pydantic import BaseModel
|
||||
|
||||
from app.database import get_db
|
||||
from app.core.deps import get_current_user
|
||||
from app.models.user import User
|
||||
from app.services.medicine import MedicineService
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
|
||||
class NaturalSearchRequest(BaseModel):
|
||||
query: str
|
||||
|
||||
|
||||
@router.get("/")
|
||||
async def search_medicines(
|
||||
q: str = Query(...),
|
||||
type: str = Query("name"),
|
||||
db: AsyncSession = Depends(get_db),
|
||||
current_user: User = Depends(get_current_user)
|
||||
):
|
||||
service = MedicineService(db)
|
||||
medicines = await service.search_medicines(q)
|
||||
return [
|
||||
{
|
||||
"id": m.id,
|
||||
"name": m.name,
|
||||
"generic_name": m.generic_name,
|
||||
"indications": m.indications,
|
||||
"total_quantity": sum(b.quantity for b in m.batches if not b.is_expired)
|
||||
}
|
||||
for m in medicines
|
||||
]
|
||||
|
||||
|
||||
@router.post("/natural")
|
||||
async def natural_language_search(
|
||||
data: NaturalSearchRequest,
|
||||
db: AsyncSession = Depends(get_db),
|
||||
current_user: User = Depends(get_current_user)
|
||||
):
|
||||
from app.ai.manager import ai_manager
|
||||
from app.config import settings
|
||||
|
||||
service = MedicineService(db)
|
||||
medicines = await service.search_medicines(data.query)
|
||||
|
||||
if not medicines:
|
||||
return {"results": [], "ai_response": "未找到相关药品"}
|
||||
|
||||
text_provider = ai_manager.get_text_provider(settings.AI_PROVIDER)
|
||||
if not text_provider:
|
||||
return {"results": [], "ai_response": "AI 服务未配置"}
|
||||
|
||||
medicines_data = [
|
||||
{"name": m.name, "indications": m.indications or ""}
|
||||
for m in medicines
|
||||
]
|
||||
|
||||
try:
|
||||
results = await text_provider.natural_language_search(data.query, medicines_data)
|
||||
return {"results": results, "ai_response": "搜索完成"}
|
||||
except Exception as e:
|
||||
return {"results": [], "ai_response": f"搜索失败: {str(e)}"}
|
||||
Reference in New Issue
Block a user