Lark AI Agent 🚀
This commit is contained in:
3
app/core/__init__.py
Normal file
3
app/core/__init__.py
Normal file
@ -0,0 +1,3 @@
|
||||
"""
|
||||
Core business logic modules
|
||||
"""
|
||||
53
app/core/llm_service.py
Normal file
53
app/core/llm_service.py
Normal file
@ -0,0 +1,53 @@
|
||||
"""
|
||||
Service for Large Language Model operations
|
||||
"""
|
||||
import json
|
||||
from loguru import logger
|
||||
from openai import OpenAI
|
||||
from app.config.settings import settings
|
||||
|
||||
class LLMService:
|
||||
"""Service for handling LLM API calls"""
|
||||
|
||||
def __init__(self):
|
||||
api_key = settings.OPENAI_API_KEY
|
||||
self.api_key = api_key
|
||||
if api_key:
|
||||
self.openai_client = OpenAI(
|
||||
api_key=api_key,
|
||||
base_url=settings.OPENAI_API_BASE_URL,
|
||||
)
|
||||
else:
|
||||
self.openai_client = None
|
||||
logger.warning("未在配置中设置 OPENAI_API_KEY")
|
||||
|
||||
def chat_completion(self, messages, tools=None, model=None):
|
||||
"""
|
||||
发送请求到OpenAI并返回回复
|
||||
|
||||
Args:
|
||||
messages: 消息列表
|
||||
tools: 工具列表
|
||||
model: 模型名称,默认使用settings中的配置
|
||||
|
||||
Returns:
|
||||
OpenAI API的响应对象
|
||||
"""
|
||||
if not self.openai_client:
|
||||
raise ValueError("OpenAI client is not initialized")
|
||||
model = model or settings.OPENAI_API_MODEL
|
||||
if tools:
|
||||
return self.openai_client.chat.completions.create(
|
||||
model=model,
|
||||
messages=messages,
|
||||
tools=tools
|
||||
)
|
||||
else:
|
||||
return self.openai_client.chat.completions.create(
|
||||
model=model,
|
||||
messages=messages
|
||||
)
|
||||
|
||||
def is_available(self):
|
||||
"""检查API是否可用"""
|
||||
return self.openai_client is not None
|
||||
179
app/core/mcp_server.py
Normal file
179
app/core/mcp_server.py
Normal file
@ -0,0 +1,179 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
import os
|
||||
import sys
|
||||
import random
|
||||
import datetime
|
||||
from loguru import logger
|
||||
from sqlalchemy import func, desc
|
||||
from mcp.server.fastmcp import FastMCP
|
||||
|
||||
|
||||
|
||||
BASE_DIR = os.path.abspath(os.path.join(os.path.dirname(__file__), '..', '..'))
|
||||
if BASE_DIR not in sys.path:
|
||||
sys.path.insert(0, BASE_DIR)
|
||||
|
||||
from app.core.llm_service import LLMService
|
||||
from app.db.session import get_db_session, close_db_session
|
||||
from app.db.models import Message
|
||||
from app.api.auth import get_auth
|
||||
from app.api.lark_client import LarkClient
|
||||
|
||||
mcp = FastMCP("LARK_MCP_SERVER")
|
||||
registered_tools = []
|
||||
llm_service = LLMService()
|
||||
|
||||
|
||||
def register_tool(name: str, description: str):
|
||||
def decorator(func):
|
||||
mcp.tool(name=name, description=description)(func)
|
||||
registered_tools.append((name, description))
|
||||
return func
|
||||
return decorator
|
||||
|
||||
@register_tool(name="list_tools", description="List all available tools and their descriptions")
|
||||
def list_tools() -> str:
|
||||
result = "🛠️ 当前可用功能列表:\n"
|
||||
for name, desc in registered_tools:
|
||||
result += f"- `{name}`:{desc}\n"
|
||||
return result
|
||||
|
||||
@register_tool(name="get_weather", description="获取城市天气")
|
||||
def get_weather(city):
|
||||
"""
|
||||
获取城市天气
|
||||
:param city: 城市名称
|
||||
:return: 城市天气
|
||||
"""
|
||||
from extension.weather_api.api import get_city_weather
|
||||
return get_city_weather(city)
|
||||
|
||||
@register_tool(name="extra_order_from_content", description="提取文字中的订单信息,包括订单号、商品名称、数量等,以json格式返回")
|
||||
def extra_order_from_content(content: str) -> str:
|
||||
"""
|
||||
提取订单信息
|
||||
:param content: 消息内容
|
||||
:return: 提取的订单信息
|
||||
"""
|
||||
res = llm_service.chat_completion(
|
||||
messages=[
|
||||
{"role": "user", "content": content},
|
||||
{"role": "system", "content": "请提取订单信息,包括订单号、商品名称、数量等,以json格式返回"},
|
||||
],
|
||||
tools=None,
|
||||
model="qwen-plus"
|
||||
)
|
||||
if res and res.choices:
|
||||
content = res.choices[0].message.content
|
||||
if content:
|
||||
return content
|
||||
return "未能提取到订单信息,请检查消息内容是否包含有效的订单信息。"
|
||||
|
||||
|
||||
@register_tool(name="tell_joke", description="Tell a random joke")
|
||||
def tell_joke() -> str:
|
||||
jokes = [
|
||||
"为什么程序员都喜欢黑色?因为他们不喜欢 bug 光。",
|
||||
"Python 和蛇有什么共同点?一旦缠上你就放不下了。",
|
||||
"为什么 Java 开发者很少被邀去派对?因为他们总是抛出异常。",
|
||||
]
|
||||
return random.choice(jokes)
|
||||
|
||||
|
||||
@register_tool(name="get_time", description="Get the current time")
|
||||
def get_time() -> str:
|
||||
now = datetime.datetime.now()
|
||||
return f"当前时间是 {now.strftime('%Y-%m-%d %H:%M:%S')}"
|
||||
|
||||
|
||||
@register_tool(name="fortune", description="Draw a random fortune")
|
||||
def fortune() -> str:
|
||||
fortunes = [
|
||||
"大吉:今天适合尝试新事物!✨",
|
||||
"中吉:平稳的一天,保持专注。",
|
||||
"小吉:会有小惊喜出现~",
|
||||
"凶:注意不要过度疲劳。",
|
||||
"大凶:小心电子设备出问题 🧯"
|
||||
]
|
||||
return random.choice(fortunes)
|
||||
|
||||
|
||||
@register_tool(name="count_daily_speakers", description="获取今天发言的人数统计")
|
||||
def count_daily_speakers() -> str:
|
||||
"""查询数据库统计今天有多少人发言"""
|
||||
db = get_db_session()
|
||||
try:
|
||||
today = datetime.datetime.now().date()
|
||||
today_start = datetime.datetime.combine(today, datetime.time.min)
|
||||
today_end = datetime.datetime.combine(today, datetime.time.max)
|
||||
speaker_count = db.query(func.count(func.distinct(Message.user_id)))\
|
||||
.filter(Message.message_time >= today_start)\
|
||||
.filter(Message.message_time <= today_end)\
|
||||
.scalar()
|
||||
message_count = db.query(func.count(Message.id))\
|
||||
.filter(Message.message_time >= today_start)\
|
||||
.filter(Message.message_time <= today_end)\
|
||||
.scalar()
|
||||
|
||||
return f"今天已有 {speaker_count} 人发言,共发送了 {message_count} 条消息。"
|
||||
except Exception as e:
|
||||
logger.error(f"查询今日发言人数时出错: {str(e)}")
|
||||
return f"查询失败: {str(e)}"
|
||||
finally:
|
||||
close_db_session(db)
|
||||
|
||||
@register_tool(name="get_top_speaker_today", description="获取今天发言最多的用户")
|
||||
def get_top_speaker_today() -> str:
|
||||
"""查询数据库统计今天谁的发言最多"""
|
||||
db = get_db_session()
|
||||
try:
|
||||
today = datetime.datetime.now().date()
|
||||
today_start = datetime.datetime.combine(today, datetime.time.min)
|
||||
today_end = datetime.datetime.combine(today, datetime.time.max)
|
||||
result = db.query(
|
||||
Message.user_name,
|
||||
Message.user_id,
|
||||
func.count(Message.id).label('message_count')
|
||||
)\
|
||||
.filter(Message.message_time >= today_start)\
|
||||
.filter(Message.message_time <= today_end)\
|
||||
.group_by(Message.user_id, Message.user_name)\
|
||||
.order_by(desc('message_count'))\
|
||||
.first()
|
||||
if not result:
|
||||
return "今天还没有人发言。"
|
||||
user_name, user_id, message_count = result
|
||||
return f"今日话题王: {user_name},共发送了 {message_count} 条消息。"
|
||||
except Exception as e:
|
||||
logger.error(f"查询今日最多发言用户时出错: {str(e)}")
|
||||
return f"查询失败: {str(e)}"
|
||||
finally:
|
||||
close_db_session(db)
|
||||
|
||||
@register_tool(name="send_message", description="给指定用户发送消息 {user:用户名称 content:消息内容}")
|
||||
def send_message(user: str, content: str) -> str:
|
||||
"""给指定用户发送私信"""
|
||||
lark_client = LarkClient(get_auth())
|
||||
SearchResponsePacket, userAndGroupIds = lark_client.search_some(user)
|
||||
if not userAndGroupIds:
|
||||
return f"未找到用户 '{user}'。"
|
||||
user_or_group_id = userAndGroupIds[0]
|
||||
if user_or_group_id['type'] == 'user':
|
||||
logger.info(f'搜索到用户: {user}')
|
||||
userId = user_or_group_id['id']
|
||||
PutChatResponsePacket, chatId = lark_client.create_chat(userId)
|
||||
found_user_name = lark_client.get_other_user_all_name(userId, chatId)
|
||||
logger.info(f'用户名称: {found_user_name}')
|
||||
else:
|
||||
logger.info('搜索到群组')
|
||||
chatId = user_or_group_id['id']
|
||||
group_name = lark_client.get_group_name(chatId)
|
||||
logger.info(f'群组名称: {group_name}')
|
||||
return f"'{user}' 是一个群组,不是用户,无法发送私信。"
|
||||
|
||||
_ = lark_client.send_msg(content, chatId)
|
||||
return f"成功向 {user} 发送了私信: '{content}'"
|
||||
|
||||
if __name__ == "__main__":
|
||||
print(get_weather("北京"))
|
||||
mcp.run(transport="stdio")
|
||||
108
app/core/message_service.py
Normal file
108
app/core/message_service.py
Normal file
@ -0,0 +1,108 @@
|
||||
"""
|
||||
Service for processing and storing Lark messages
|
||||
"""
|
||||
import json
|
||||
import os
|
||||
|
||||
from loguru import logger
|
||||
from datetime import datetime
|
||||
from app.db.models import Message
|
||||
from app.db.session import get_db_session, close_db_session
|
||||
from app.config.settings import settings
|
||||
from app.core.llm_service import LLMService
|
||||
from fastmcp import Client
|
||||
from fastmcp.client.transports import PythonStdioTransport
|
||||
|
||||
class MessageService:
|
||||
"""Service for processing and storing messages"""
|
||||
|
||||
def __init__(self, lark_client):
|
||||
self.lark_client = lark_client
|
||||
self.db = get_db_session()
|
||||
self.llm_service = LLMService()
|
||||
self.mcp_transport = PythonStdioTransport("app/core/mcp_server.py", env={"PATHEXT": os.environ.get("PATHEXT", "")})
|
||||
self.system_message = {"role": "system", "content": "你是一个很有帮助的助手。当用户提问需要调用工具时,请使用 tools 中定义的函数。"}
|
||||
|
||||
async def process_message(self, user_name, user_id, content, is_group_chat, group_name, chat_id):
|
||||
"""Process and store a message in the database"""
|
||||
try:
|
||||
message_source = f"群聊 {group_name}" if is_group_chat else "私聊"
|
||||
logger.info(f"收到{message_source}消息 - 用户: {user_name}, 内容: {content}")
|
||||
if not content or not content.strip():
|
||||
logger.warning("收到非纯文本消息,跳过存储")
|
||||
return
|
||||
message = Message(
|
||||
user_name=user_name,
|
||||
user_id=user_id,
|
||||
content=content,
|
||||
is_group_chat=is_group_chat,
|
||||
group_name=group_name,
|
||||
chat_id=chat_id,
|
||||
message_time=datetime.now()
|
||||
)
|
||||
self.db.add(message)
|
||||
self.db.commit()
|
||||
if content.strip().startswith(settings.FUNCTION_TRIGGER_FLAG):
|
||||
await self._handle_function_call(user_name, content, chat_id, is_group_chat)
|
||||
except Exception as e:
|
||||
self.db.rollback()
|
||||
logger.error(f"存储消息时出错: {str(e)}")
|
||||
|
||||
|
||||
async def _handle_function_call(self, user_name, content, chat_id, is_group_chat):
|
||||
"""处理flag触发的函数调用请求并发送响应"""
|
||||
try:
|
||||
logger.info(f"触发flag函数调用 - 用户: {user_name}, 内容: {content}")
|
||||
query = content.strip()[len(settings.FUNCTION_TRIGGER_FLAG):].strip()
|
||||
if not self.llm_service.is_available():
|
||||
error_msg = "未在配置中设置 OPENAI_API_KEY"
|
||||
logger.error(error_msg)
|
||||
self.lark_client.send_msg(error_msg, chat_id)
|
||||
return
|
||||
|
||||
async with Client(self.mcp_transport) as mcp_client:
|
||||
tools = []
|
||||
for tool in await mcp_client.list_tools():
|
||||
info = tool.model_dump() if hasattr(tool, "model_dump") else tool.dict()
|
||||
tools.append({
|
||||
"type": "function",
|
||||
"function": {
|
||||
"name": info["name"],
|
||||
"description": info.get("description", ""),
|
||||
"parameters": info.get("parameters", {})
|
||||
}
|
||||
})
|
||||
messages = [
|
||||
self.system_message,
|
||||
{"role": "user", "content": query}
|
||||
]
|
||||
resp = self.llm_service.chat_completion(messages, tools)
|
||||
msg = resp.choices[0].message
|
||||
if msg.tool_calls:
|
||||
call = msg.tool_calls[0]
|
||||
fn_name = call.function.name
|
||||
args = json.loads(call.function.arguments)
|
||||
output = await mcp_client.call_tool(fn_name, args)
|
||||
logger.info(f"调用函数 {fn_name} -> {output}")
|
||||
messages.append(msg)
|
||||
messages.append({
|
||||
"role": "tool",
|
||||
"content": output,
|
||||
"tool_call_id": call.id
|
||||
})
|
||||
summary = self.llm_service.chat_completion(messages)
|
||||
response = summary.choices[0].message.content
|
||||
else:
|
||||
response = msg.content
|
||||
self.lark_client.send_msg(response, chat_id)
|
||||
except Exception as e:
|
||||
logger.error(f"处理flag函数调用时出错: {str(e)}")
|
||||
error_msg = f"执行错误: {str(e)}"
|
||||
try:
|
||||
self.lark_client.send_msg(error_msg, chat_id)
|
||||
except Exception as send_err:
|
||||
logger.error(f"发送错误消息失败: {str(send_err)}")
|
||||
|
||||
def close(self):
|
||||
"""Close database session"""
|
||||
close_db_session(self.db)
|
||||
Reference in New Issue
Block a user