### FileSystem MCP server configuration example Source: https://docs.sayu-bot.com/AIFeatures/MCP.html Example of a FileSystem MCP server configuration; replace /path/to/allowed/dir with your allowed directory. ```json { "name": "FileSystem", "command": "npx", "args": ["-y", "@modelcontextprotocol/server-filesystem", "/path/to/allowed/dir"], "env": {}, "enabled": true } ``` -------------------------------- ### Complete YAML Skill example with parameters Source: https://docs.sayu-bot.com/AIFeatures/Skills.html Complete YAML Skill example for a character assistant. Includes a parameters section with required and optional parameters, and tools list. ```yaml # res/ai_core/skills/character_assistant.yaml name: character_assistant description: 原神角色助手 instructions: | 你是原神角色助手,专门帮助玩家了解角色信息。 ## 角色信息范围 - 基础属性(生命值、攻击力、防御力) - 技能介绍(普通攻击、元素战技、元素爆发) - 天赋效果 - 命之座效果 - 培养材料 - 推荐武器 - 推荐圣遗物 ## 回复风格 - 使用中文回复 - 数据准确,来源可靠 - 适当使用表格展示数据 - 重要信息加粗显示 parameters: - name: character_name type: string description: 角色名称 required: true - name: info_type type: string description: 信息类型(基础/技能/天赋/命座/材料/武器/圣遗物) required: false default: 基础 tools: - search_knowledge - query_character_build ``` -------------------------------- ### Register a KnowledgePoint for a game guide Source: https://docs.sayu-bot.com/AIFeatures/KnowledgeBase.html Registers a KnowledgePoint for a game guide, including detailed monster config and team recommendations. Use for structured game guides. ```python from gsuid_core.ai_core.register import ai_entity from gsuid_core.ai_core.models import KnowledgePoint # 注册游戏攻略 ai_entity(KnowledgePoint( id="genshin_guide_001", plugin="Genshin", title="深境螺旋 12 层攻略", content=""" # 深境螺旋 12 层攻略 ## 怪物配置 - 12-1 上半: 遗迹守卫 x2 - 12-1 下半: 深渊法师 x3 - 12-2 上半: 恒常机关阵列 - 12-2 下半: 魔偶剑鬼 - 12-3 上半: 空壳怪组合 - 12-3 下半: 深海龙蜥 ## 推荐配队 ### 上半 - 队伍1: 雷神 + 班尼特 + 香菱 + 行秋 - 队伍2: 胡桃 + 钟离 + 夜兰 + 阿贝多 ### 下半 - 队伍1: 神里绫华 + 申鹤 + 万叶 + 心海 - 队伍2: 甘雨 + 温迪 + 莫娜 + 迪奥娜 ## 注意事项 1. 注意怪物抗性 2. 合理分配能量 3. 利用元素反应 """, tags=["原神", "深境螺旋", "攻略", "12层"], )) ``` -------------------------------- ### MiniMax MCP server configuration example Source: https://docs.sayu-bot.com/AIFeatures/MCP.html Example of a MiniMax MCP server configuration; place your actual API key in the env field. ```json { "name": "MiniMax", "command": "uvx", "args": ["minimax-coding-plan-mcp"], "env": {"MINIMAX_API_KEY": "your_api_key_here"}, "enabled": true } ``` -------------------------------- ### Register a KnowledgeBase for a character Source: https://docs.sayu-bot.com/AIFeatures/KnowledgeBase.html Basic example of registering a KnowledgeBase for a character, including markdown content and tags. Call this during plugin initialization. ```python from gsuid_core.ai_core.register import ai_entity from gsuid_core.ai_core.models import KnowledgeBase # 在插件初始化时调用 ai_entity(KnowledgeBase( id="genshin_character_001", plugin="Genshin", title="雷电将军 - 角色介绍", content=""" # 雷电将军 ## 角色信息 - 元素: 雷 - 武器: 长枪 - 命之座: 万世之座 ## 技能简介 ### 普通攻击 - 源流 枪类的普通攻击... ### 元素战技 - 奥义 - 梦想真说 展现梦想的力量... """, tags=["原神", "雷电将军", "雷神", "角色"], )) ``` -------------------------------- ### Basic YAML Skill example with instructions and tools Source: https://docs.sayu-bot.com/AIFeatures/Skills.html Basic YAML structure for a Skill. Defines name, description, instructions (with Chinese guidance), and a list of tools. ```yaml # res/ai_core/skills/game_guide.yaml name: game_guide description: 游戏攻略查询技能 instructions: | 你是一个游戏攻略助手,专门帮助玩家查询游戏信息。 ## 能力 1. 查询角色培养攻略 2. 查询武器推荐 3. 查询圣遗物搭配 4. 查询队伍搭配建议 ## 回复格式 1. 先确认玩家的问题 2. 提供详细的攻略信息 3. 给出具体的数值建议 4. 询问是否还有其他问题 tools: - search_knowledge - query_character_info - query_weapon_info ``` -------------------------------- ### Create simple agent with create_agent Source: https://docs.sayu-bot.com/AIFeatures/Agent.html Creates a simple agent with a system prompt for translation, then uses it in an asynchronous function. The example prints the translation result. ```python from gsuid_core.ai_core.gs_agent import create_agent # 创建自定义 Agent agent = create_agent( system_prompt=""" 你是一个翻译助手,负责将中文翻译成英文。 只翻译用户输入的内容,不要添加任何解释。 """, ) # 在异步函数中使用 async def translate_text(text: str) -> str: result = await agent.run(text) return result # 使用结果 result = await translate_text("你好,世界!") print(result) # Hello, world! ``` -------------------------------- ### Add manual knowledge via ManualKnowledgeBase Source: https://docs.sayu-bot.com/AIFeatures/KnowledgeBase.html Example of adding a manual knowledge entry using ManualKnowledgeBase. It will not be synced at startup, use for runtime content. ```python from gsuid_core.ai_core.register import add_manual_knowledge from gsuid_core.ai_core.models import ManualKnowledgeBase add_manual_knowledge(ManualKnowledgeBase( id="manual_faq_001", plugin="custom", title="常见问题回答", content="""Q: 如何绑定账号? A: 发送 '绑定 123456' 即可。 Q: 如何查询角色信息? A: 发送 '角色信息 角色名' 即可。""", tags=["FAQ", "绑定"], )) ``` -------------------------------- ### my_plugin/__init__.py 插件初始化与 /help 命令 Source: https://docs.sayu-bot.com/AIFeatures/ai_core_api_for_plugins.html 主插件初始化文件,用于注册插件别名和导入 AI 工具模块以触发工具注册,并定义一个 `/help` 命令来展示插件使用指南。该代码在导入时自动执行别名注册。 ```python from gsuid_core.sv import SV from gsuid_core.ai_core.register import ai_alias # 注册别名(导入时自动执行) ai_alias("我的插件", ["MyPlugin", "mp"]) # 导入 AI 工具模块(触发工具注册) from my_plugin import ai_tools # noqa: F401 # 注册插件命令 sv = SV("我的插件") @sv.on_fullmatch("/help") async def show_help(bot, ev): await bot.send(""" 我的插件使用指南: - /help: 显示此帮助 - /bind : 绑定账号 - /query <角色>: 查询角色 AI功能: - 直接@机器人并描述需求,AI会自动调用相关工具 """) ``` -------------------------------- ### 命令触发器: on_command Source: https://docs.sayu-bot.com/CodePlugins/trigger.html on_command triggers when the message starts with the command and fires even without a following argument. It is like on_fullmatch plus on_prefix; examples like '命令测试 ABC' trigger it. ```python @sv_switch.on_command('命令测试') async def get_command_msg(bot: Bot, ev: Event): await bot.send('正在进行[命令测试]') await asyncio.sleep(2) await bot.send('[命令测试]校验成功!') ``` -------------------------------- ### 在 __init__ 中引用配置 Source: https://docs.sayu-bot.com/CodePlugins/CookBook.html 在 __init__.py 中相对引用 config.py 中定义的 tq_config,并通过 get_config('tq_key').data 获取配置值。 ```python # 相对引用上面定义的配置 from .config import tq_config # KEY直接调用配置项,配置名称要填入,然后引用data属性 KEY = tq_config.get_config('tq_key').data ``` -------------------------------- ### 前缀触发器: on_prefix Source: https://docs.sayu-bot.com/CodePlugins/trigger.html on_prefix triggers when the message starts with the given prefixes. Unlike on_command, it requires a following argument; the message '开启' alone will not trigger. The example toggles services based on the prefix and ev.text. ```python @sv_switch.on_prefix(('关闭', '开启')) async def get_switch_msg(bot: Bot, ev: Event): name = ev.text if not name: return await bot.send('正在进行[关闭/开启开关]') if name in SL.lst: if ev.command == '关闭': SL.lst[name].disable() await bot.send('关闭成功!') else: SL.lst[name].enable() await bot.send('开启成功!') else: await bot.send('未找到该服务...') ``` -------------------------------- ### Incomplete Markdown Skill example (daily_assistant.md) Source: https://docs.sayu-bot.com/AIFeatures/Skills.html Incomplete Markdown example. Only a comment line is present in the source; the rest of the example is not shown. ```markdown ``` -------------------------------- ### on_core_start 函数定义 Source: https://docs.sayu-bot.com/CodePlugins/Class.html 注册在 WS 服务启动之后作为后台任务异步执行的钩子函数,适合网络请求、模型下载等耗时操作。 ```python def on_core_start( func: Optional[Callable] = None, /, priority: int = 0, ): ``` -------------------------------- ### on_core_start 使用示例 Source: https://docs.sayu-bot.com/CodePlugins/Class.html 展示如何使用 on_core_start 装饰器注册启动后钩子,用于耗时的初始化操作。 ```python from gsuid_core.server import on_core_start @on_core_start async def my_hook(): # 耗时的初始化操作,不影响 WS 连接 ... ``` -------------------------------- ### Install plugin (User mode) with nb Source: https://docs.sayu-bot.com/LinkBots/NoneBot2.html Checks the current version of Node.js installed on the system. ```sh nb plugin install nonebot-plugin-genshinuid ``` -------------------------------- ### on_core_start_before 函数定义 Source: https://docs.sayu-bot.com/CodePlugins/Class.html 注册在 WS 服务启动之前执行的钩子函数,用于数据库迁移、全局变量加载等必须在连接建立前完成的操作。 ```python def on_core_start_before( func: Optional[Callable] = None, /, priority: int = 0, ): ``` -------------------------------- ### on_core_start_before 启动前钩子示例 Source: https://docs.sayu-bot.com/CodePlugins/Start.html 展示如何使用 on_core_start_before 装饰器注册启动前钩子,该钩子在 WS 服务启动前阻塞执行,适合数据库迁移等操作。支持通过 priority 参数设置优先级。 ```python from gsuid_core.server import on_core_start_before @on_core_start_before async def my_before_hook(): # 必须在 WS 连接前完成的操作 ... @on_core_start_before(priority=5) async def my_before_hook_with_priority(): # 带优先级的启动前钩子 ... ``` -------------------------------- ### on_core_start_before 使用示例 Source: https://docs.sayu-bot.com/CodePlugins/Class.html 展示如何使用 on_core_start_before 装饰器注册启动前钩子,包括无参数和带优先级两种用法。 ```python from gsuid_core.server import on_core_start_before @on_core_start_before async def my_before_hook(): # 必须在 WS 连接前完成的操作 ... @on_core_start_before(priority=5) async def my_before_hook_with_priority(): ... ``` -------------------------------- ### Custom Python MCP server configuration example Source: https://docs.sayu-bot.com/AIFeatures/MCP.html Example of a custom Python MCP server configuration; set the API_KEY environment variable for your server. ```json { "name": "MyCustomMCP", "command": "python", "args": ["-m", "my_mcp_server"], "env": {"API_KEY": "your_key"}, "enabled": true } ``` -------------------------------- ### Example: search_latest_news using web_search Source: https://docs.sayu-bot.com/AIFeatures/BuiltinTools.html Example usage of web_search inside an AI tool function. It searches for the latest news on a given topic, requesting 3 results. ```python from gsuid_core.ai_core.buildin_tools import web_search from pydantic_ai import RunContext from gsuid_core.ai_core.models import ToolContext @ai_tools() async def search_latest_news( ctx: RunContext[ToolContext], topic: str, ) -> str: """ 搜索最新资讯 Args: topic: 搜索主题 """ result = await web_search( ctx, query=f"{topic} 最新资讯", num_results=3, ) return result ``` -------------------------------- ### 为插件设置强制前缀 (Plugins force_prefix) Source: https://docs.sayu-bot.com/CodePlugins/PluginsPrefix.html 在插件起始位置 __init__.py 中调用 Plugins 并设置 force_prefix 为 ['雀魂', 'qh'],allow_empty_prefix 为 False,使插件内任意命令都必须携带前缀 '雀魂' 或 'qh'。 ```python from gsuid_core.sv import Plugins Plugins( name="MajsoulUID", force_prefix=['雀魂', 'qh'], allow_empty_prefix=False ) ``` -------------------------------- ### 绘制插件帮助图(get_new_help) Source: https://docs.sayu-bot.com/CodePlugins/PluginsHelp.html 使用Core内置函数`get_new_help()`绘制插件帮助图。需要准备`help.json`、素材(banner_bg和bg宽度保持1545)以及150x150的PNG透明图标。通过`get_plugin_available_prefix`获取前缀,并传递`user_pm`实现不同权限显示不同内容。 ```python import json from typing import Dict from pathlib import Path import aiofiles from PIL import Image from gsuid_core.sv import get_plugin_available_prefix from gsuid_core.help.model import PluginHelp from gsuid_core.help.draw_new_plugin_help import get_new_help from ..utils.image import get_footer from ..version import MajsoulUID_version ICON = Path(__file__).parent.parent.parent / 'ICON.png' HELP_DATA = Path(__file__).parent / 'help.json' ICON_PATH = Path(__file__).parent / 'icon_path' TEXT_PATH = Path(__file__).parent / 'texture2d' # 使用Core内置函数`get_plugin_available_prefix`获取插件可用的前缀 PREFIX = get_plugin_available_prefix('MajsoulUID') # 使用aiofiles异步读取help.json文件 async def get_help_data() -> Dict[str, PluginHelp]: async with aiofiles.open(HELP_DATA, 'rb') as file: return json.loads(await file.read()) async def get_help(user_pm: int): return await get_new_help( # 插件名 plugin_name='MajsoulUID', # 插件的badge, 会出现在帮助图title的右边的色块 # 该值是一个dict, key为内容, value为色块颜色(RGB数组或者字符串) plugin_info={f'v{MajsoulUID_version}': ''}, # 插件的logo plugin_icon=Image.open(ICON), # 之前准备的help.json文件 plugin_help=await get_help_data(), # 插件的前缀, 哪怕存在用户自定义, 也可以让帮助图可以给出正确的命令 plugin_prefix=PREFIX, # 主题, 暂时只影响整体的文字颜色, 如果是dark, 文字则为白色, light则为黑色 help_mode='dark', # 帮助图最上面的部分, 一些精彩的插画非常适合, 注意处理宽度为1545 banner_bg=Image.open(TEXT_PATH / 'banner_bg.jpg'), # 帮助图最上面部分的副标题, 可以写一些个性化内容 banner_sub_text='小心八木唯!', # 帮助图背景, 注意处理宽度为1545! # 请尽量使用纯色背景, 如果是插画, 尽量添加高斯模糊或者颜色遮罩! help_bg=Image.open(TEXT_PATH / 'bg.jpg'), # 分类的横幅, 注意处理宽度为1545! cag_bg=Image.open(TEXT_PATH / 'cag_bg.png'), # 单个命令的底部图片, 大小为490x175 item_bg=Image.open(TEXT_PATH / 'item.png'), # 命令图标包, 大小为150x150 icon_path=ICON_PATH, # 页脚 footer=get_footer(), # 是否允许缓存, 或者每次使用命令均重新绘制(建议使用缓存) enable_cache=True, # 为了让不同权限等级,触发帮助的人展现不同的帮助菜单,需要传递ev.user_pm中的权限信息 pm=user_pm, ) ``` -------------------------------- ### Example: notify_user using send_message_by_ai Source: https://docs.sayu-bot.com/AIFeatures/BuiltinTools.html Example usage of send_message_by_ai inside an AI tool function. It sends a text message to a target user, or to the current user if target_user is not provided. ```python from gsuid_core.ai_core.buildin_tools import send_message_by_ai from pydantic_ai import RunContext from gsuid_core.ai_core.models import ToolContext @ai_tools() async def notify_user( ctx: RunContext[ToolContext], message: str, target_user: Optional[str] = None, ) -> str: """ 通知用户 Args: message: 通知内容 target_user: 目标用户ID,不填则通知当前用户 """ result = await send_message_by_ai( ctx, message_type="text", text=message, user_id=target_user, ) return result ``` -------------------------------- ### get_current_date - get current date time Source: https://docs.sayu-bot.com/AIFeatures/ai_core_api_for_plugins.html Tool to get the current date and time. Accepts an optional timezone parameter that defaults to 'Asia/Shanghai'. Category is 'default', making it available to the AI agent. ```python @ai_tools(category="default") async def get_current_date( ctx: RunContext[ToolContext], timezone: str = "Asia/Shanghai", # 时区 ) -> str ``` -------------------------------- ### 导入 WeatherBind 类(__init__.py) Source: https://docs.sayu-bot.com/CodePlugins/CookBook.html 在插件主文件中导入刚创建的数据库模型类,以便后续使用。 ```python from .database import WeatherBind ``` -------------------------------- ### Example: query_game_info using search_knowledge Source: https://docs.sayu-bot.com/AIFeatures/BuiltinTools.html Example usage of search_knowledge inside an AI tool function. It queries the knowledge base for character information and skills, restricting the search to the 'Genshin' plugin and limiting results to 5. ```python from gsuid_core.ai_core.buildin_tools import search_knowledge from pydantic_ai import RunContext from gsuid_core.ai_core.models import ToolContext @ai_tools() async def query_game_info( ctx: RunContext[ToolContext], character_name: str, ) -> str: """ 查询游戏角色信息 Args: character_name: 角色名称 """ result = await search_knowledge( ctx, query=f"{character_name}的角色信息和技能", plugin="Genshin", # 限定在原神插件知识库中检索 limit=5, ) return result ``` -------------------------------- ### Startup flow for MCP tools registration Source: https://docs.sayu-bot.com/AIFeatures/MCP.html Startup flow: on_core_start hook (priority=5) calls register_all_mcp_tools(), which reads enabled configs, creates MCPClient, lists tools, wraps them, and registers to _TOOL_REGISTRY["mcp"]. ```text 框架启动 │ ├── on_core_start 钩子 (priority=5) │ │ │ └── register_all_mcp_tools() │ │ │ ├── 从 mcp_config_manager 获取所有 enabled=true 的配置 │ ├── 对每个配置创建 MCPClient 并调用 list_tools() │ ├── 为每个 MCP 工具动态创建包装函数 │ └── 注册到 _TOOL_REGISTRY["mcp"] │ └── AI Agent 通过 search_tools() 发现并调用 MCP 工具 ``` -------------------------------- ### ai_entity - 插件知识注册 Source: https://docs.sayu-bot.com/AIFeatures/ai_core_api_for_plugins.html Registers plugin knowledge via ai_entity. The first block shows imports, the second shows the function signature, and the third is a usage example with fields like id, plugin, title, and content. The example is incomplete as shown. ```python from gsuid_core.ai_core.register import ai_entity from gsuid_core.ai_core.models import KnowledgePoint ``` ```python def ai_entity(entity: Union[KnowledgePoint, KnowledgeBase]) -> None ``` ```python from gsuid_core.ai_core.register import ai_entity from gsuid_core.ai_core.models import KnowledgePoint ai_entity(KnowledgePoint( id="genshin_character_shogun", plugin="GenshinUID", title="雷电将军 - 角色介绍", content="" ``` -------------------------------- ### 创建角色攻略 Agent 并注册插件处理命令 Source: https://docs.sayu-bot.com/AIFeatures/Examples.html 创建角色攻略 Agent,用于回答角色培养相关问题。定义系统提示词,能力范围包括角色定位、武器选择、圣遗物搭配、天赋升级优先级和队伍搭配,并规定了回复格式。注册插件时创建 SV 实例和 Plugin 实例,设置权限等级 pm=1。然后定义命令处理:\"/myplugin help\" 显示帮助信息,正则命令 \"/query (.+)\" 调用 agent 生成角色攻略回复。这些代码块共同构成一个完整插件的初始化与命令处理流程。 ```python # ==================== 创建专用 Agent ==================== # 创建角色攻略 Agent character_guide_agent = create_agent( system_prompt=""" 你是角色攻略专家,专门帮助玩家了解角色培养。 ## 能力范围 1. 分析角色定位(主C/副C/辅助) 2. 推荐武器选择 3. 推荐圣遗物搭配 4. 提供天赋升级优先级 5. 推荐队伍搭配 ## 回复格式 1. **角色定位**: 简要说明角色定位 2. **培养建议**: 武器/圣遗物/天赋 3. **队伍搭配**: 推荐配队方案 4. **注意事项**: 使用技巧和注意事项 """, ) ``` ```python # ==================== 插件注册 ==================== sv_myplugin = SV("我的插件") pd_mp = Plugin( name="我的插件", pm=1, sv=sv_myplugin, ) ``` ```python # ==================== 命令处理 ==================== @pd_mp.on_fullmatch("/myplugin help") async def show_help(bot: Bot, ev: Event): """显示帮助""" help_text = """ 【我的插件】帮助信息 【基础命令】 /help - 显示本帮助 /query 角色名 - 查询角色信息 /build 角色名 - 查询配装推荐 【AI功能】 直接发送问题,AI助手会为您解答 【示例】 /query 丝柯克 /build 达达利亚 输出 丝柯克怎么培养? """ await bot.send(help_text) ``` ```python @pd_mp.on_regex(r"/query (.+)") async def handle_query(bot: Bot, ev: Event): """处理查询命令""" character = ev.regex_group[1] # 使用 Agent 生成回复 result = await character_guide_agent.run( user_message=f"请介绍角色 {character} 的培养攻略", bot=bot, ev=ev, ) await bot.send(result) ``` -------------------------------- ### 使用 to_ai 参数注册 AI 工具 Source: https://docs.sayu-bot.com/CodePlugins/CookBook.html 在 on_command 装饰器中添加 to_ai 参数,将命令注册为 AI 工具。AI 根据描述理解何时调用,并通过 ai_return 返回文本摘要。 ```python from gsuid_core.sv import SV from gsuid_core.bot import Bot from gsuid_core.models import Event from gsuid_core.ai_core.trigger_bridge import ai_return gs_weather_info = SV('天气信息查询') @gs_weather_info.on_command( '天气', block=True, to_ai="""查询指定城市的天气信息。 当用户询问天气、气温、是否下雨等问题时调用。 Args: text: 城市名称,例如 "北京"、"上海"、"漳州" """, ) async def send_weather_msg(bot: Bot, ev: Event): text = ev.text.strip() if not text: # 检查是否有绑定城市 uuid = await WeatherBind.get_uid_by_game(ev.user_id, ev.bot_id) if uuid is None: ai_return("错误:用户未绑定城市且未提供城市名称") return await bot.send('请输入城市名称,或使用 tq绑定城市 命令!') pos_id, pos_name = uuid.split('|') else: # ... 原有的城市查询逻辑 ... pass # ... 原有的天气查询逻辑 ... # 在发送前注入 AI 可读的文本摘要 ai_return(f"【{pos_name}天气】温度:{now_temp}度,体感温度:{now_feels}度") await bot.send(text) ``` -------------------------------- ### Schedule Jobs with cron, interval, and date Triggers Source: https://docs.sayu-bot.com/CodePlugins/Scheduler.html Three trigger types for APScheduler jobs: cron for scheduled times (example: daily at 8:30), interval for repeated intervals (example: every 30 minutes), and date for one-time execution using add_job with trigger='date' and run_date. ```python @scheduler.scheduled_job('cron', hour=8, minute=30) ``` ```python @scheduler.scheduled_job('interval', minutes=30) ``` ```python scheduler.add_job(func, trigger='date', run_date=...) ``` -------------------------------- ### send_trigger_images tool return value example Source: https://docs.sayu-bot.com/AIFeatures/ai_core_api_for_plugins.html 展示 AI 工具返回值的示例,说明当触发器生成图片时,AI 需要调用 send_trigger_images 工具将图片真正发送给用户;如果不调用,图片会被丢弃。 ```python # AI 工具返回值示例: # "[已生成 1 张图片,存储在本次工具上下文中。请调用 send_trigger_images 工具将图片发送给用户]" ``` -------------------------------- ### 注册图片实体并检索 ai_image / search_and_load_image Source: https://docs.sayu-bot.com/AIFeatures/ai_core_api_for_plugins.html 注册图片实体到 AI 知识库并检索使用。先导入 ai_image 和 ImageEntity,调用 ai_image 注册图片,之后通过 search_and_load_image 语义检索图片。ImageEntity 字段中 id, plugin, path, tags, content 必填;source 固定为 'plugin',_hash 传入空字符串即可。 ```python from gsuid_core.ai_core.register import ai_image from gsuid_core.ai_core.models import ImageEntity ``` ```python def ai_image(entity: ImageEntity) -> None ``` ```python from gsuid_core.ai_core.register import ai_image from gsuid_core.ai_core.models import ImageEntity aio_image(ImageEntity( id="genshin_hutao_illustration", plugin="GenshinUID", path="./resources/characters/hutao.png", tags=["胡桃", "原神", "角色立绘", "火元素"], content="胡桃角色立绘图片,往生堂第七十七代堂主,性格活泼爱捉弄人。", source="plugin", _hash="", )) ``` ```python from gsuid_core.ai_core.rag import search_and_load_image # 在插件命令处理中使用 async def show_character_image(bot, ev): image = await search_and_load_image("给我看看胡桃的图片") if image: await bot.send(image) ``` -------------------------------- ### get_self_persona_info - Get Self Persona Info Source: https://docs.sayu-bot.com/AIFeatures/ai_core_api_for_plugins.html Retrieves persona information of the AI itself, such as config, image, avatar, or audio. ```APIDOC ## get_self_persona_info ### Description Retrieves persona information of the AI itself, such as config, image, avatar, or audio. ### Method Async function call (AI tool, category="buildin") ### Signature ```python @ai_tools(category="buildin") async def get_self_persona_info( ctx: RunContext[ToolContext], info_type: Literal["config", "image", "avatar", "audio"], persona_name: str, ) -> str ``` ### Parameters - **ctx** (RunContext[ToolContext]) - Required - The run context. - **info_type** (Literal["config", "image", "avatar", "audio"]) - Required - The type of information to retrieve. - **persona_name** (str) - Required - The persona name. ### Returns - **str** - The requested persona information. ### info_type Details - `"config"` - Returns `config.json` configuration content (JSON string, excluding introduction). - `"image"` - Returns the illustration image path. - `"avatar"` - Returns the avatar image path. - `"audio"` - Returns the audio file path. ``` -------------------------------- ### Create agent with skills and use skill via create_agent Source: https://docs.sayu-bot.com/AIFeatures/Skills.html Creates an agent with specific skills in the system prompt, then defines an async function to use a skill by name. Fetches the skill from the skills collectioncloaking a fallback if missing, and runs the agent with the skill's instructions. ```python from gsuid_core.ai_core.gs_agent import create_agent from gsuid_core.ai_core.skills import skills_toolset # 创建 Agent 时指定使用特定 skills agent = create_agent( system_prompt=""" 你是一个游戏助手,可以使用以下技能: - game_guide: 查询游戏攻略 - character_assistant: 查询角色信息 """, ) # 使用 skill 工具集 async def use_skill(skill_name: str, query: str) -> str: skill = skills.get(skill_name) if not skill: return f"Skill {skill_name} 不存在" # 使用 skill 的 instructions agent = create_agent(system_prompt=skill.instructions) result = await agent.run(query) return result ``` -------------------------------- ### 消息触发器: on_message Source: https://docs.sayu-bot.com/CodePlugins/trigger.html on_message triggers on any received message. Useful for logging all messages or global processing; this example responds to every message. ```python @sv_switch.on_message() async def message_trigger(bot: Bot, ev: Event): await bot.send('收到消息,正在处理...') await asyncio.sleep(1) await bot.send(f'处理完成:{ev.text}') ``` -------------------------------- ### 后缀触发器: on_suffix Source: https://docs.sayu-bot.com/CodePlugins/trigger.html on_suffix triggers when the message ends with one of the given suffixes. This example responds to messages ending with .jpg or .png. ```python @sv_switch.on_suffix(('.jpg', '.png')) async def suffix_trigger(bot: Bot, ev: Event): await bot.send('检测到图片后缀,正在处理!') # 添加后续逻辑 await asyncio.sleep(1) await bot.send(f'处理完成:{ev.text}') ```