Function Calling 调度体系
掌握 Eridanus 中 dynamic_imports、function_declarations 声明规范、上下文注入与工具管控机制
在 Eridanus 中,CoreReply 对话中枢能够调用点歌、抽卡、查动态或下载视频等功能,依赖的是框架内置的 Function Calling(工具调用)体系(核心加载器位于 func_map_loader.py 与 core_reply)。
1. 调度链路概览
[群友发消息] -> "Yucca,帮我下载一下这个 B 站视频呗:https://b23.tv/xxx"
↓
[CoreReply 思考]
- 携带所有已注册插件导出的 function_declarations 向 LLM 发起意图分析
↓
[LLM 返回 Tool Call 请求]
- 工具名: "download_video"
- 抽取出的模型参数: {"url": "https://b23.tv/xxx", "platform": "bilibili", "type": "video"}
↓
[框架核心路由执行]
- 根据 dynamic_imports 找到 "run.streaming_media.youtube" 中的 download_video
- 自动注入上下文对象:download_video(bot, event, config, url=..., platform=..., type=...)
↓
[工具执行完毕]
- 若返回 None:流程结束,不再调用大模型(适合已自行完成发图/清记录的静默工具)
- 若返回 dict:将数据作为 Tool Output 再次喂给 LLM,触发 CoreReply 二次生成人格化回复2. __init__.py 三要素声明
在 Eridanus 中,每个具备工具调用能力的插件目录(位于 run/<插件名>/ 下)必须在其 __init__.py 中声明以下三个元数据:
plugin_description:字符串,向插件扫描器简短描述本插件的服务定位。dynamic_imports:字典映射,告诉底层func_map_loader该函数位于哪个 Python 模块下,用于动态按需导入。function_declarations:符合 Gemini / OpenAPI Schema 规范的工具描述列表,包含name、description和parameters。
源码示例:run/streaming_media/__init__.py
# 位于 run/streaming_media/__init__.py
plugin_description = "媒体服务"
# 1. 动态导入映射表:模块完整路径 -> [导出的函数名称列表]
dynamic_imports = {
"run.streaming_media.youtube": ["download_video"],
"run.streaming_media.cloud_music_parsing": ["parse_cloud_music"]
}
# 2. 供大模型理解的工具参数 Schema
function_declarations = [
{
"name": "download_video",
"description": "下载youtube/bilibili的视频或音频。",
"parameters": {
"type": "object",
"properties": {
"type": {
"type": "string",
"enum": ["video", "audio"],
"description": "下载类型。asmr100平台只能下载audio"
},
"url": {
"type": "string",
"description": "视频/音频的链接地址"
},
"platform": {
"type": "string",
"enum": ["youtube", "bilibili", "asmr100"],
"description": "视频的来源平台。域名为b23.tv的为bilibili"
}
},
"required": [
"url",
"platform"
]
}
},
{
"name": "parse_cloud_music",
"description": "解析并下载网易云音乐单曲",
"parameters": {
"type": "object",
"properties": {
"url": {
"type": "string",
"description": "音频的链接地址"
}
},
"required": [
"url"
]
}
}
]不要在外层嵌套多余结构
在 function_declarations 中,每个条目直接是 {"name": ..., "description": ..., "parameters": ...} 的扁平字典。不要在外层额外包装 {"type": "function", "function": ...},底层 LLM 适配器在发送前会根据具体 API 自行包装。
3. 函数签名约定:(bot, event, config)
工具入参固定约定
无论工具接收多少个大模型传入的业务参数,函数签名的前三个位置参数必须固定为:
async def your_tool_func(bot: ExtendBot, event, config: YAMLManager, ...):为什么不在 function_declarations 中声明这三个参数?
这三个对象属于框架内部的系统上下文:
bot:ExtendBot实例,用于发送消息、语音或图片;event:触发本次调用的消息事件(包含user_id、group_id、pure_text等);config:全局配置热重载单例管理器(YAMLManager)。
大模型只需从对话中提取业务参数(如 url、platform、target),底层 build_tool_fixed_params() 在调用函数时会自动将 (bot, event, config) 传入前三个形参。
纯上下文工具示例
下面的清除上下文工具不需要大模型传递任何额外参数:
async def clear_chat_history(bot: ExtendBot, event, config: YAMLManager):
"""清除当前用户在本会话的 CoreReply 对话历史"""
ctx = ContextManager(config)
group_id = getattr(event, "group_id", None)
# 直接利用传入的 event 和 config 结算业务
ctx.clear_session(group_id, event.user_id)
# 直接通过传入的 bot 发送反馈给用户
await bot.send(event, "好的,对话记录已清除~")4. 返回值设计与 CoreReply 二次调用
工具执行完毕后是否触发 AI 二次回复,由函数返回值决定:
返回 None:静默结束
如果工具内部已经通过 await bot.send(...) 发送了最终结果,直接返回 None(或不写 return)。CoreReply 检测到返回为空时,本次对话链路直接结束,不会再触发大模型回复,避免多余的 Token 消耗。
返回 dict:触发 CoreReply 二次调用
如果工具负责查询数据或抽卡,并希望 AI 结合角色人设对结果进行组织和回复,函数必须返回一个 Python dict。CoreReply 会捕获该字典作为 Tool Output 提交回大模型,由模型生成最终回复。
源码示例:塔罗牌占卜工具(call_tarot)
import random
from developTools.message.message_components import Text, Image
from framework_common.framework_util.manshuo_draw import manshuo_draw
async def call_tarot(bot, event, config):
# 1. 检查彩蛋牌分支
if (config.basic_plugin.config["tarot"]["彩蛋牌"] and
random.randint(1, 100) < config.basic_plugin.config["tarot"]["彩蛋牌"]["probability"]):
cards_ = config.basic_plugin.config["tarot"]["彩蛋牌"]["card_index"]
card = random.choice(cards_)
card_path, text = list(card.items())[0]
if text == "":
text = "no description"
# 工具内部先发一张牌面图片
await bot.send(event, [Text(f"{text}"), Image(file=card_path)])
# 返回字典,供 CoreReply 获取彩蛋信息并组织解说
return {"text": "开出彩蛋牌,来源:jojo的奇妙冒险", "img": card_path}
# 2. 普通牌面分支:渲染长图后发送
txt, img, tarots = tarotChoice('bilibili')
await bot.send(event, Image(file=(
await manshuo_draw([
{'type': 'basic_set', 'img_width': 750, 'img_name_save': f'{event.pure_text}_{tarots}.png'},
{'type': 'img', 'subtype': 'common_with_des_right', 'img': [img], 'content': [txt]}
])
)))
# 将抽卡结果字典返回给 core_reply,触发 AI 结合牌意解卦
return {"text": txt, "img": img}5. 从零编写带 Function Calling 的插件
下面以新增“群积分小金库查询”工具为例:
第一步:创建插件目录结构
run/gold_vault/
├── __init__.py # 存放元数据、dynamic_imports 与 function_declarations
└── service.py # 存放具体实现的异步工具函数第二步:编写 run/gold_vault/__init__.py
plugin_description = "小金库积分服务"
dynamic_imports = {
"run.gold_vault.service": ["query_user_coins"]
}
function_declarations = [
{
"name": "query_user_coins",
"description": "查询当前群友或指定成员的小金库金币余额与钱包等级",
"parameters": {
"type": "object",
"properties": {
"target_name": {
"type": "string",
"description": "要查询的用户昵称,若用户询问自己的资产则填'self'"
}
},
"required": ["target_name"]
}
}
]第三步:编写 run/gold_vault/service.py
from framework_common.database_util.User import get_user
async def query_user_coins(bot, event, config, target_name: str):
"""前三个参数永远是 bot, event, config;第四个参数对应 parameters 里的 target_name"""
# 从数据库中读取用户数据
user = await get_user(event.user_id)
coin_count = user.coin
# 返回结构化 dict,触发 CoreReply 二次生成回复
return {
"user_id": event.user_id,
"target": target_name,
"coins": coin_count,
"wallet_status": "富得流油" if coin_count > 1000 else "穷得叮当响"
}6. 运行期热刷新工具
如果在运行过程中动态生成或修改了工具(例如通过 cli_bridge 生成代码),无需重启整个机器人进程,直接调用热刷新接口即可:
from run.core_reply.service.reply_engine import refresh_tools
# 触发全盘重新扫描 run/ 目录并无损更新内存中的工具缓存字典
refresh_tools()底层 func_map_loader.py 会清空 dynamic_imports 并通过 importlib.reload 重新载入修改后的声明。
7. 工具管控中心(function_control.json)
将所有插件的工具描述一次性传入 System Prompt 会导致上下文与 Token 消耗膨胀,同时降低模型选择工具的准确率。为此,框架引入了全局工具管控文件 run/core_reply/function_control.json:
{
"disabled": [
"anime_game_service_func_collection",
"call_aiArtModerate",
"call_bangumi_search",
"call_character_identify",
"call_clear_all_history",
"call_delete_user_history",
"call_fortune",
"call_tts",
"call_user_data_query",
"garbage_collection",
"get_all_speakers",
"operate_group_censor",
"parse_cloud_music",
"search_with_official_api"
],
"disabled_skills": [
"reply-live-test"
]
}工作机制:
- 动态过滤:
ReplyEngine每次调用大模型前,都会通过function_control.load_disabled()实时比对并剔除被禁用的工具。 - 零重启解禁:需要启用某个工具(如
parse_cloud_music或call_fortune)时,在 WebUI 中将其从disabled列表中移除即可在下一轮对话生效。 - 默认精简高开销工具:默认配置已禁用
garbage_collection(低频维护)、call_character_identify(高开销图像识别)等工具,以降低日常对话的 Token 消耗。