Files
agent_management/agent_templates/agents/facebook_agent/agent/facebook_agent.py
T

101 lines
3.0 KiB
Python

"""
Facebook搜索智能Agent
基于Pydantic AI框架实现(简化版本,直接使用客户端)
"""
from typing import List, Optional
from loguru import logger
# 支持相对导入和绝对导入
try:
from ..config import Config
from ..models.schemas import SearchRequest, SearchResponse, SearchResultItem
from ..clients.facebook_client import FacebookClient
from ..clients.litellm_client import LiteLLMClient
except ImportError:
# 如果相对导入失败,尝试绝对导入
from config import Config
from models.schemas import SearchRequest, SearchResponse, SearchResultItem
from clients.facebook_client import FacebookClient
from clients.litellm_client import LiteLLMClient
# 定义Agent依赖类型
class FacebookAgentDeps:
"""Agent依赖项"""
def __init__(self, config: Config):
self.config = config
self.facebook_client = FacebookClient(config)
self.llm_client = LiteLLMClient(config)
class FacebookAgent:
"""Facebook搜索Agent包装类"""
def __init__(self, config: Config):
"""
初始化Agent
Args:
config: 配置对象
"""
self.config = config
self.deps = FacebookAgentDeps(config)
logger.info("FacebookAgent 初始化完成")
async def search(self, request: SearchRequest) -> SearchResponse:
"""
执行搜索
Args:
request: 搜索请求
Returns:
搜索响应
"""
try:
# 直接调用搜索工具获取结果
search_results = await self.deps.facebook_client.search(
request.query,
request.limit
)
# 生成总结
summary = None
if search_results:
try:
results_dict = [
{
"title": r.title,
"snippet": r.snippet,
"author": r.author,
"likes": r.likes
}
for r in search_results
]
summary = await self.deps.llm_client.generate_summary(
request.query,
results_dict
)
except Exception as e:
logger.warning(f"生成总结失败: {e}")
return SearchResponse(
success=True,
query=request.query,
results=search_results,
total_count=len(search_results),
summary=summary
)
except Exception as e:
logger.error(f"搜索过程出错: {e}")
return SearchResponse(
success=False,
query=request.query,
results=[],
message=f"搜索失败: {str(e)}"
)