product_tools.py 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. # app/services/agent/tools/builtin/product_tools.py
  2. from typing import Optional, Dict, Any, List
  3. from sqlalchemy.ext.asyncio import AsyncSession
  4. from sqlalchemy import select, or_, desc
  5. from app.models.product import VasProduct
  6. from app.services.agent.tools.registry import agent_tool
  7. @agent_tool(
  8. name="search_products",
  9. description="检索可用的增值服务/签证/产品列表,支持按国家、签证类型或关键词搜索",
  10. )
  11. async def search_products(
  12. keyword: Optional[str] = None,
  13. country: Optional[str] = None,
  14. visa_type: Optional[str] = None,
  15. limit: int = 10,
  16. *,
  17. db: AsyncSession,
  18. ) -> Dict[str, Any]:
  19. """搜索并列出可用的产品"""
  20. limit = max(1, min(limit, 30))
  21. stmt = select(VasProduct).where(VasProduct.enabled == 1)
  22. if country and country.strip():
  23. stmt = stmt.where(VasProduct.country.ilike(f"%{country.strip()}%"))
  24. if visa_type and visa_type.strip():
  25. stmt = stmt.where(VasProduct.visa_type.ilike(f"%{visa_type.strip()}%"))
  26. if keyword and keyword.strip():
  27. kw = f"%{keyword.strip()}%"
  28. stmt = stmt.where(or_(VasProduct.title.ilike(kw), VasProduct.description.ilike(kw)))
  29. stmt = stmt.order_by(desc(VasProduct.recommend_score), desc(VasProduct.id)).limit(limit)
  30. res = await db.execute(stmt)
  31. products = res.scalars().all()
  32. items = []
  33. for p in products:
  34. items.append({
  35. "product_id": p.id,
  36. "title": p.title,
  37. "country": p.country,
  38. "city": p.city,
  39. "visa_type": p.visa_type,
  40. "price_amount": p.price_amount,
  41. "currency": p.price_currency,
  42. "description": p.description[:200] if p.description else "",
  43. })
  44. return {
  45. "count": len(items),
  46. "products": items,
  47. }
  48. @agent_tool(
  49. name="get_product_detail",
  50. description="获取指定商品ID的详细信息与配置说明",
  51. )
  52. async def get_product_detail(
  53. product_id: int,
  54. *,
  55. db: AsyncSession,
  56. ) -> Dict[str, Any]:
  57. """获取单个产品的详细信息"""
  58. stmt = select(VasProduct).where(VasProduct.id == product_id)
  59. res = await db.execute(stmt)
  60. p = res.scalar_one_or_none()
  61. if not p:
  62. return {"error": f"商品 ID {product_id} 不存在"}
  63. return {
  64. "product_id": p.id,
  65. "title": p.title,
  66. "country": p.country,
  67. "city": p.city,
  68. "visa_type": p.visa_type,
  69. "provider": p.provider,
  70. "price_amount": p.price_amount,
  71. "currency": p.price_currency,
  72. "enabled": bool(p.enabled),
  73. "description": p.description,
  74. "extra_fields": p.extra_fields,
  75. "schema_id": p.schema_id,
  76. }