From 46ffa826e55164a8e0dd224c74d2df70d229e546 Mon Sep 17 00:00:00 2001 From: SengokuCola <1026294844@qq.com> Date: Fri, 23 May 2025 15:36:01 +0800 Subject: [PATCH] =?UTF-8?q?feat=EF=BC=9A=E6=96=B0=E5=A2=9E=E8=B1=86?= =?UTF-8?q?=E5=8C=85=E7=BB=98=E5=9B=BE=E7=A4=BA=E4=BE=8B=E6=8F=92=E4=BB=B6?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../info_processors/self_processor.py | 11 +- .../planners/actions/plugin_action.py | 58 ++++- .../test_plugin/actions/mute_action.py | 2 +- src/plugins/test_plugin_pic/__init__.py | 5 + .../test_plugin_pic/actions/__init__.py | 5 + .../actions/generate_pic_config.py | 48 ++++ .../test_plugin_pic/actions/pic_action.py | 246 ++++++++++++++++++ .../actions/pic_action_config.toml | 24 ++ 8 files changed, 391 insertions(+), 8 deletions(-) create mode 100644 src/plugins/test_plugin_pic/__init__.py create mode 100644 src/plugins/test_plugin_pic/actions/__init__.py create mode 100644 src/plugins/test_plugin_pic/actions/generate_pic_config.py create mode 100644 src/plugins/test_plugin_pic/actions/pic_action.py create mode 100644 src/plugins/test_plugin_pic/actions/pic_action_config.toml diff --git a/src/chat/focus_chat/info_processors/self_processor.py b/src/chat/focus_chat/info_processors/self_processor.py index 0b65fe77c..881e6682f 100644 --- a/src/chat/focus_chat/info_processors/self_processor.py +++ b/src/chat/focus_chat/info_processors/self_processor.py @@ -33,12 +33,13 @@ def init_prompt(): 现在请你根据现有的信息,思考自我认同 1. 你是一个什么样的人,你和群里的人关系如何 -2. 思考有没有人提到你,或者图片与你有关 -3. 你的自我认同是否有助于你的回答,如果你需要自我相关的信息来帮你参与聊天,请输出,否则请输出十个字以内的简短自我认同 -4. 一般情况下不用输出自我认同,只需要输出十几个字的简短自我认同就好,除非有明显需要自我认同的场景 +2. 你的形象是什么 +3. 思考有没有人提到你,或者图片与你有关 +4. 你的自我认同是否有助于你的回答,如果你需要自我相关的信息来帮你参与聊天,请输出,否则请输出十几个字的简短自我认同 +5. 一般情况下不用输出自我认同,只需要输出十几个字的简短自我认同就好,除非有明显需要自我认同的场景 -请思考的平淡一些,简短一些,说中文,不要浮夸,平淡一些。 -请注意不要输出多余内容(包括前后缀,冒号和引号,括号(),表情包,at或 @等 )。只输出自我认同内容。 +输出内容平淡一些,说中文,不要浮夸,平淡一些。 +请注意不要输出多余内容(包括前后缀,冒号和引号,括号(),表情包,at或 @等 )。只输出自我认同内容,记得明确说明这是你的自我认同。 """ Prompt(indentify_prompt, "indentify_prompt") diff --git a/src/chat/focus_chat/planners/actions/plugin_action.py b/src/chat/focus_chat/planners/actions/plugin_action.py index 10f346e15..a0cb79941 100644 --- a/src/chat/focus_chat/planners/actions/plugin_action.py +++ b/src/chat/focus_chat/planners/actions/plugin_action.py @@ -1,11 +1,15 @@ import traceback from typing import Tuple, Dict, List, Any, Optional -from src.chat.focus_chat.planners.actions.base_action import BaseAction +from src.chat.focus_chat.planners.actions.base_action import BaseAction, register_action from src.chat.heart_flow.observation.chatting_observation import ChattingObservation from src.chat.focus_chat.hfc_utils import create_empty_anchor_message from src.common.logger_manager import get_logger from src.chat.person_info.person_info import person_info_manager from abc import abstractmethod +import os +import inspect +import yaml # 或者 import json 如果你偏好 JSON +import toml # 导入 toml 库 logger = get_logger("plugin_action") @@ -15,13 +19,16 @@ class PluginAction(BaseAction): 封装了主程序内部依赖,提供简化的API接口给插件开发者 """ + action_config_file_name: Optional[str] = None # 插件可以覆盖此属性来指定配置文件名 - def __init__(self, action_data: dict, reasoning: str, cycle_timers: dict, thinking_id: str, **kwargs): + def __init__(self, action_data: dict, reasoning: str, cycle_timers: dict, thinking_id: str, global_config: Optional[dict] = None, **kwargs): """初始化插件动作基类""" super().__init__(action_data, reasoning, cycle_timers, thinking_id) # 存储内部服务和对象引用 self._services = {} + self._global_config = global_config # 存储全局配置的只读引用 + self.config: Dict[str, Any] = {} # 用于存储插件自身的配置 # 从kwargs提取必要的内部服务 if "observations" in kwargs: @@ -32,6 +39,53 @@ class PluginAction(BaseAction): self._services["chat_stream"] = kwargs["chat_stream"] self.log_prefix = kwargs.get("log_prefix", "") + self._load_plugin_config() # 初始化时加载插件配置 + + def _load_plugin_config(self): + """ + 加载插件自身的配置文件。 + 配置文件应与插件模块在同一目录下。 + 插件可以通过覆盖 `action_config_file_name` 类属性来指定文件名。 + 如果 `action_config_file_name` 未指定,则不加载配置。 + 仅支持 TOML (.toml) 格式。 + """ + if not self.action_config_file_name: + logger.debug(f"{self.log_prefix} 插件 {self.__class__.__name__} 未指定 action_config_file_name,不加载插件配置。") + return + + try: + plugin_module_path = inspect.getfile(self.__class__) + plugin_dir = os.path.dirname(plugin_module_path) + config_file_path = os.path.join(plugin_dir, self.action_config_file_name) + + if not os.path.exists(config_file_path): + logger.warning(f"{self.log_prefix} 插件 {self.__class__.__name__} 的配置文件 {config_file_path} 不存在。") + return + + file_ext = os.path.splitext(self.action_config_file_name)[1].lower() + + if file_ext == '.toml': + with open(config_file_path, 'r', encoding='utf-8') as f: + self.config = toml.load(f) or {} + logger.info(f"{self.log_prefix} 插件 {self.__class__.__name__} 的配置已从 {config_file_path} 加载。") + else: + logger.warning(f"{self.log_prefix} 不支持的插件配置文件格式: {file_ext}。仅支持 .toml。插件配置未加载。") + self.config = {} #确保未加载时为空字典 + return + + except Exception as e: + logger.error(f"{self.log_prefix} 加载插件 {self.__class__.__name__} 的配置文件 {self.action_config_file_name} 时出错: {e}") + self.config = {} # 出错时确保 config 是一个空字典 + + def get_global_config(self, key: str, default: Any = None) -> Any: + """ + 安全地从全局配置中获取一个值。 + 插件应使用此方法读取全局配置,以保证只读和隔离性。 + """ + if self._global_config: + return self._global_config.get(key, default) + logger.debug(f"{self.log_prefix} 尝试访问全局配置项 '{key}',但全局配置未提供。") + return default async def get_user_id_by_person_name(self, person_name: str) -> Tuple[str, str]: """根据用户名获取用户ID""" diff --git a/src/plugins/test_plugin/actions/mute_action.py b/src/plugins/test_plugin/actions/mute_action.py index 0e8178129..c46bc18b8 100644 --- a/src/plugins/test_plugin/actions/mute_action.py +++ b/src/plugins/test_plugin/actions/mute_action.py @@ -25,7 +25,7 @@ class MuteAction(PluginAction): "当千石可乐或可乐酱要求你禁言时使用", "当你想回避某个话题时使用", ] - default = True # 不是默认动作,需要手动添加到使用集 + default = False # 不是默认动作,需要手动添加到使用集 async def process(self) -> Tuple[bool, str]: """处理测试动作""" diff --git a/src/plugins/test_plugin_pic/__init__.py b/src/plugins/test_plugin_pic/__init__.py new file mode 100644 index 000000000..5242f1408 --- /dev/null +++ b/src/plugins/test_plugin_pic/__init__.py @@ -0,0 +1,5 @@ +"""测试插件包:图片发送""" + +""" +这是一个测试插件,用于测试图片发送功能 +""" diff --git a/src/plugins/test_plugin_pic/actions/__init__.py b/src/plugins/test_plugin_pic/actions/__init__.py new file mode 100644 index 000000000..e35417865 --- /dev/null +++ b/src/plugins/test_plugin_pic/actions/__init__.py @@ -0,0 +1,5 @@ +"""测试插件动作模块""" + +# 导入所有动作模块以确保装饰器被执行 +from . import pic_action # noqa + diff --git a/src/plugins/test_plugin_pic/actions/generate_pic_config.py b/src/plugins/test_plugin_pic/actions/generate_pic_config.py new file mode 100644 index 000000000..023333e4c --- /dev/null +++ b/src/plugins/test_plugin_pic/actions/generate_pic_config.py @@ -0,0 +1,48 @@ +import os + +CONFIG_CONTENT = """\ +# 请替换为您的火山引擎 Access Key ID +volcano_ak = "YOUR_VOLCANO_ENGINE_ACCESS_KEY_ID_HERE" +# 请替换为您的火山引擎 Secret Access Key +volcano_sk = "YOUR_VOLCANO_ENGINE_SECRET_ACCESS_KEY_HERE" +# 火山方舟 API 的基础 URL +base_url = "https://ark.cn-beijing.volces.com/api/v3" +# 默认图片生成模型 +default_model = "doubao-seedream-3-0-t2i-250415" +# 默认图片尺寸 +default_size = "1024x1024" +# 用于图片生成的API密钥 +# PicAction 当前配置为在HTTP请求体和Authorization头中使用此密钥。 +# 如果您的API认证方式不同,请相应调整或移除。 +volcano_generate_api_key = "YOUR_VOLCANO_GENERATE_API_KEY_HERE" + +# 是否默认开启水印 +default_watermark = true +# 默认引导强度 +default_guidance_scale = 2.5 +# 默认随机种子 +default_seed = 42 + +# 更多插件特定配置可以在此添加... +# custom_parameter = "some_value" +""" + +def generate_config(): + # 获取当前脚本所在的目录 + current_dir = os.path.dirname(os.path.abspath(__file__)) + config_file_path = os.path.join(current_dir, "pic_action_config.toml") + + if not os.path.exists(config_file_path): + try: + with open(config_file_path, "w", encoding="utf-8") as f: + f.write(CONFIG_CONTENT) + print(f"配置文件已生成: {config_file_path}") + print("请记得编辑该文件,填入您的火山引擎 AK/SK 和 API 密钥。") + except IOError as e: + print(f"错误:无法写入配置文件 {config_file_path}。原因: {e}") + else: + print(f"配置文件已存在: {config_file_path}") + print("未进行任何更改。如果您想重新生成,请先删除或重命名现有文件。") + +if __name__ == "__main__": + generate_config() \ No newline at end of file diff --git a/src/plugins/test_plugin_pic/actions/pic_action.py b/src/plugins/test_plugin_pic/actions/pic_action.py new file mode 100644 index 000000000..ae72ff6b5 --- /dev/null +++ b/src/plugins/test_plugin_pic/actions/pic_action.py @@ -0,0 +1,246 @@ +import asyncio +import json # 新增:用于处理JSON数据 +import urllib.request # 新增:用于发起HTTP请求 +import urllib.error # 新增:用于处理HTTP错误 +import base64 # 新增:用于Base64编码 +import traceback # 新增:用于打印堆栈跟踪 +from typing import Tuple +from src.chat.focus_chat.planners.actions.plugin_action import PluginAction, register_action +from src.common.logger_manager import get_logger +from .generate_pic_config import generate_config + +# 尝试导入 volcenginesdkarkruntime,如果失败则记录错误并在后续处理中提示用户 +# 即使我们现在主要用HTTP,这个检查也可以保留,以防未来需要或其他功能使用 +try: + from volcenginesdkarkruntime import Ark + VOLCENGINE_SDK_AVAILABLE = True +except ImportError: + VOLCENGINE_SDK_AVAILABLE = False + Ark = None # 占位,避免 NameError + +logger = get_logger("pic_action") + +generate_config() + + +@register_action +class PicAction(PluginAction): + """根据描述使用火山引擎HTTP API生成图片的动作处理类""" + + action_name = "pic_action" + action_description = ( + "可以根据特定的描述,使用火山引擎模型生成并发送一张图片 (通过HTTP API)" + ) + action_parameters = { + "description": "图片描述,输入你想要生成并发送的图片的描述,必填", + "size": "图片尺寸,例如 '1024x1024' (可选, 默认从配置或 '1024x1024')", + } + action_require = [ + "当有人要求你生成并发送一张图片时使用", + "当有人让你画一张图时使用", + ] + default = False + action_config_file_name = "pic_action_config.toml" + + def __init__(self, action_data: dict, reasoning: str, cycle_timers: dict, thinking_id: str, global_config: dict = None, **kwargs): + super().__init__(action_data, reasoning, cycle_timers, thinking_id, global_config, **kwargs) + + if not VOLCENGINE_SDK_AVAILABLE: + logger.warning(f"{self.log_prefix} Volcengine SDK (volcenginesdkarkruntime) 未找到. PicAction将仅依赖HTTP配置.") + else: + logger.info(f"{self.log_prefix} Volcengine SDK 可用, 但PicAction配置为优先HTTP方式.") + + http_base_url = self.config.get("base_url") + http_api_key = self.config.get("volcano_generate_api_key") + + if not (http_base_url and http_api_key): + logger.error(f"{self.log_prefix} PicAction初始化, 但HTTP配置 (base_url 或 volcano_generate_api_key) 缺失. HTTP图片生成将失败.") + else: + logger.info(f"{self.log_prefix} HTTP方式初始化完成. Base URL: {http_base_url}, API Key已配置.") + + # _restore_env_vars 方法不再需要,已移除 + + async def process(self) -> Tuple[bool, str]: + """处理图片生成动作(通过HTTP API)""" + logger.info(f"{self.log_prefix} 执行 pic_action (HTTP): {self.reasoning}") + + http_base_url = self.config.get("base_url") + http_api_key = self.config.get("volcano_generate_api_key") + + if not (http_base_url and http_api_key): + error_msg = "抱歉,图片生成功能所需的HTTP配置(如API地址或密钥)不完整,无法提供服务。" + await self.send_message_by_expressor(error_msg) + logger.error(f"{self.log_prefix} HTTP调用配置缺失: base_url 或 volcano_generate_api_key.") + return False, "HTTP配置不完整" + + description = self.action_data.get("description") + if not description: + logger.warning(f"{self.log_prefix} 图片描述为空,无法生成图片。") + await self.send_message_by_expressor("你需要告诉我想要画什么样的图片哦~") + return False, "图片描述为空" + + default_model = self.config.get("default_model", "doubao-seedream-3-0-t2i-250415") + image_size = self.action_data.get("size", self.config.get("default_size", "1024x1024")) + + # guidance_scale 现在完全由配置文件控制 + guidance_scale_input = self.config.get("default_guidance_scale", 2.5) # 默认2.5 + guidance_scale_val = 2.5 # Fallback default + try: + guidance_scale_val = float(guidance_scale_input) + except (ValueError, TypeError): + logger.warning(f"{self.log_prefix} 配置文件中的 default_guidance_scale 值 '{guidance_scale_input}' 无效 (应为浮点数),使用默认值 2.5。") + guidance_scale_val = 2.5 + + # Seed parameter - ensure it's always an integer + seed_config_value = self.config.get("default_seed") + seed_val = 42 # Default seed if not configured or invalid + if seed_config_value is not None: + try: + seed_val = int(seed_config_value) + except (ValueError, TypeError): + logger.warning(f"{self.log_prefix} 配置文件中的 default_seed ('{seed_config_value}') 无效,将使用默认种子 42。") + # seed_val is already 42 + else: + logger.info(f"{self.log_prefix} 未在配置中找到 default_seed,将使用默认种子 42。建议在配置文件中添加 default_seed。") + # seed_val is already 42 + + # Watermark 现在完全由配置文件控制 + effective_watermark_source = self.config.get("default_watermark", True) # 默认True + if isinstance(effective_watermark_source, bool): + watermark_val = effective_watermark_source + elif isinstance(effective_watermark_source, str): + watermark_val = effective_watermark_source.lower() == 'true' + else: + logger.warning(f"{self.log_prefix} 配置文件中的 default_watermark 值 '{effective_watermark_source}' 无效 (应为布尔值或 \'true\'/'false\'),使用默认值 True。") + watermark_val = True + + await self.send_message_by_expressor(f"收到!正在为您生成关于 '{description}' 的图片,请稍候...(模型: {default_model}, 尺寸: {image_size})") + + try: + success, result = await asyncio.to_thread( + self._make_http_image_request, + prompt=description, + model=default_model, + size=image_size, + seed=seed_val, + guidance_scale=guidance_scale_val, + watermark=watermark_val + ) + except Exception as e: + logger.error(f"{self.log_prefix} (HTTP) 异步请求执行失败: {e!r}", exc_info=True) + traceback.print_exc() + success = False + result = f"图片生成服务遇到意外问题: {str(e)[:100]}" + + if success: + image_url = result + logger.info(f"{self.log_prefix} 图片URL获取成功: {image_url[:70]}... 下载并编码.") + + try: + encode_success, encode_result = await asyncio.to_thread( + self._download_and_encode_base64, + image_url + ) + except Exception as e: + logger.error(f"{self.log_prefix} (B64) 异步下载/编码失败: {e!r}", exc_info=True) + traceback.print_exc() + encode_success = False + encode_result = f"图片下载或编码时发生内部错误: {str(e)[:100]}" + + if encode_success: + base64_image_string = encode_result + send_success = await self.send_message(type="emoji", data=base64_image_string) + if send_success: + await self.send_message_by_expressor("图片表情已发送!") + return True, "图片表情已发送" + else: + await self.send_message_by_expressor("图片已处理为Base64,但作为表情发送失败了。") + return False, "图片表情发送失败 (Base64)" + else: + await self.send_message_by_expressor(f"获取到图片URL,但在处理图片时失败了:{encode_result}") + return False, f"图片处理失败(Base64): {encode_result}" + else: + error_message = result + await self.send_message_by_expressor(f"哎呀,生成图片时遇到问题:{error_message}") + return False, f"图片生成失败: {error_message}" + + def _download_and_encode_base64(self, image_url: str) -> Tuple[bool, str]: + """下载图片并将其编码为Base64字符串""" + logger.info(f"{self.log_prefix} (B64) 下载并编码图片: {image_url[:70]}...") + try: + with urllib.request.urlopen(image_url, timeout=30) as response: + if response.status == 200: + image_bytes = response.read() + base64_encoded_image = base64.b64encode(image_bytes).decode('utf-8') + logger.info(f"{self.log_prefix} (B64) 图片下载编码完成. Base64长度: {len(base64_encoded_image)}") + return True, base64_encoded_image + else: + error_msg = f"下载图片失败 (状态: {response.status})" + logger.error(f"{self.log_prefix} (B64) {error_msg} URL: {image_url}") + return False, error_msg + except Exception as e: # Catches all exceptions from urlopen, b64encode, etc. + logger.error(f"{self.log_prefix} (B64) 下载或编码时错误: {e!r}", exc_info=True) + traceback.print_exc() + return False, f"下载或编码图片时发生错误: {str(e)[:100]}" + + def _make_http_image_request(self, prompt: str, model: str, size: str, seed: int | None, guidance_scale: float, watermark: bool) -> Tuple[bool, str]: + base_url = self.config.get("base_url") + generate_api_key = self.config.get("volcano_generate_api_key") + + endpoint = f"{base_url.rstrip('/')}/images/generations" + + payload_dict = { + "model": model, + "prompt": prompt, + "response_format": "url", + "size": size, + "guidance_scale": guidance_scale, + "watermark": watermark, + "seed": seed, # seed is now always an int from process() + "api-key": generate_api_key + } + # if seed is not None: # No longer needed, seed is always an int + # payload_dict["seed"] = seed + + data = json.dumps(payload_dict).encode('utf-8') + headers = { + "Content-Type": "application/json", + "Accept": "application/json", + "Authorization": f"Bearer {generate_api_key}" + } + + logger.info(f"{self.log_prefix} (HTTP) 发起图片请求: {model}, Prompt: {prompt[:30]}... To: {endpoint}") + logger.debug(f"{self.log_prefix} (HTTP) Request Headers: {{...Authorization: Bearer {generate_api_key[:10]}...}}") + logger.debug(f"{self.log_prefix} (HTTP) Request Body (api-key omitted): {json.dumps({k: v for k, v in payload_dict.items() if k != 'api-key'})}") + + req = urllib.request.Request(endpoint, data=data, headers=headers, method="POST") + + try: + with urllib.request.urlopen(req, timeout=60) as response: + response_status = response.status + response_body_bytes = response.read() + response_body_str = response_body_bytes.decode('utf-8') + + logger.info(f"{self.log_prefix} (HTTP) 响应: {response_status}. Preview: {response_body_str[:150]}...") + + if 200 <= response_status < 300: + response_data = json.loads(response_body_str) + image_url = None + if isinstance(response_data.get("data"), list) and response_data["data"] and isinstance(response_data["data"][0], dict): + image_url = response_data["data"][0].get("url") + elif response_data.get("url"): + image_url = response_data.get("url") + + if image_url: + logger.info(f"{self.log_prefix} (HTTP) 图片生成成功,URL: {image_url[:70]}...") + return True, image_url + else: + logger.error(f"{self.log_prefix} (HTTP) API成功但无图片URL. 响应预览: {response_body_str[:300]}...") + return False, "图片生成API响应成功但未找到图片URL" + else: + logger.error(f"{self.log_prefix} (HTTP) API请求失败. 状态: {response.status}. 正文: {response_body_str[:300]}...") + return False, f"图片API请求失败(状态码 {response.status})" + except Exception as e: + logger.error(f"{self.log_prefix} (HTTP) 图片生成时意外错误: {e!r}", exc_info=True) + traceback.print_exc() + return False, f"图片生成HTTP请求时发生意外错误: {str(e)[:100]}" diff --git a/src/plugins/test_plugin_pic/actions/pic_action_config.toml b/src/plugins/test_plugin_pic/actions/pic_action_config.toml new file mode 100644 index 000000000..2d2b55a3e --- /dev/null +++ b/src/plugins/test_plugin_pic/actions/pic_action_config.toml @@ -0,0 +1,24 @@ +# 请替换为您的火山引擎 Access Key ID +volcano_ak = "YOUR_VOLCANO_ENGINE_ACCESS_KEY_ID_HERE" +# 请替换为您的火山引擎 Secret Access Key +volcano_sk = "YOUR_VOLCANO_ENGINE_SECRET_ACCESS_KEY_HERE" +# 火山方舟 API 的基础 URL +base_url = "https://ark.cn-beijing.volces.com/api/v3" +# 默认图片生成模型 +default_model = "doubao-seedream-3-0-t2i-250415" +# 默认图片尺寸 +default_size = "1024x1024" +# 用于图片生成的API密钥 +# PicAction 当前配置为在HTTP请求体和Authorization头中使用此密钥。 +# 如果您的API认证方式不同,请相应调整或移除。 +volcano_generate_api_key = "YOUR_VOLCANO_GENERATE_API_KEY_HERE" + +# 是否默认开启水印 +default_watermark = true +# 默认引导强度 +default_guidance_scale = 2.5 +# 默认随机种子 +default_seed = 42 + +# 更多插件特定配置可以在此添加... +# custom_parameter = "some_value"