AstrBot icon indicating copy to clipboard operation
AstrBot copied to clipboard

[Feature]当模型不支持视觉的时候,获取其他模型对图片的转述

Open Rt39 opened this issue 1 year ago • 8 comments

发生了什么

因为我选择的火山方舟deepseek的api,而deepseek api不支持图片,因此我打开了图片转述功能,使用chatgpt-4o-mini希望将图片转换为文字,但我发现AstrBot\packages\astrbot\long_term_memory.py中的handle_message()过滤了所有非群聊信息,从而导致发送信息请求失败。尝试进行如下修改

    async def handle_message(self, event: AstrMessageEvent):
        '''都合补丁'''
        final_message = ""

        if event.get_message_type() == MessageType.FRIEND_MESSAGE:
            comp = event.get_messages()[-1]
            if isinstance(comp, Plain):
                final_message += f" {comp.text}"
            elif isinstance(comp, Image):
                # image_urls.append(comp.url if comp.url else comp.file)
                if self.image_caption:
                    try:
                        caption = await self.get_image_caption(
                            comp.url if comp.url else comp.file
                        )
                        final_message += f" [Image: {caption}]"
                    except Exception as e:
                        logger.error(f"获取图片描述失败: {e}")
                else:
                    final_message += " [Image]"

        if event.get_message_type() == MessageType.GROUP_MESSAGE:
            datetime_str = datetime.datetime.now().strftime("%H:%M:%S")

            final_message = f"[{event.message_obj.sender.nickname}/{datetime_str}]: "

            for comp in event.get_messages():
                if isinstance(comp, Plain):
                    final_message += f" {comp.text}"
                elif isinstance(comp, Image):
                    # image_urls.append(comp.url if comp.url else comp.file)
                    if self.image_caption:
                        try:
                            caption = await self.get_image_caption(
                                comp.url if comp.url else comp.file
                            )
                            final_message += f" [Image: {caption}]"
                        except Exception as e:
                            logger.error(f"获取图片描述失败: {e}")
                    else:
                        final_message += " [Image]"
        logger.debug(f"ltm | {event.unified_msg_origin} | {final_message}")
        self.session_chats[event.unified_msg_origin].append(final_message)
        if len(self.session_chats[event.unified_msg_origin]) > self.max_cnt:
            self.session_chats[event.unified_msg_origin].pop(0)

在传递的消息中的确调用了图像转述,但仍然提示参数错误,暂时不清楚如何改变传递prompt的类型,希望提供技术帮助

如何复现?

打开图像转述功能,发送私聊即可复现

AstrBot 版本与部署方式

本地部署 3.4.27 Windows 10

操作系统

Windows

额外信息

 [22:11:44| DEBUG] [aiocqhttp_platform_adapter.py:78]: aiocqhttp: 收到消息: [{'type': 'image', 'data': {'summary': '', 'file': '7E6C3D48EB2FDA4FD214F2DCB8AAA6CE.png', 'sub_type': 0, 'url': 'https://multimedia.nt.qq.com.cn/download?appid=1406&fileid=EhQfMUztr48Q1XrKbVBO-cPnEJ_DrRiLmBQg_gooxomDpJzHiwMyBHByb2RaEHwoXhC5GpLJADI0CiVOX3o&rkey=CAMSKMa3OFokB_TlMny3-PJX-KpSayWFw8sLPxVnc4PbiCjZw7Tsp2awMHk', 'file_size': '330763'}}]
 [22:11:44| INFO] [event_bus.py:21]: [aiocqhttp] 山里灵活的狗/123456789: [图片]
 [22:11:44| DEBUG] [scheduler.py:22]: 执行阶段 WakingCheckStage
 [22:11:44| DEBUG] [scheduler.py:22]: 执行阶段 WhitelistCheckStage
 [22:11:44| DEBUG] [scheduler.py:22]: 执行阶段 RateLimitStage
 [22:11:44| DEBUG] [scheduler.py:22]: 执行阶段 ContentSafetyCheckStage
 [22:11:44| DEBUG] [scheduler.py:22]: 执行阶段 PreProcessStage
 [22:11:44| DEBUG] [scheduler.py:22]: 执行阶段 ProcessStage
 [22:11:44| DEBUG] [star_request.py:34]: 执行插件 handler packages.astrbot.main_on_message
 [22:11:53| DEBUG] [openai_source.py:77]: completion: ChatCompletion(id='chatcmpl-B1PMOVdaYrW3IKNnNVMeDYTrSBO9W', choices=[Choice(finish_reason='stop', index=0, logprobs=None, message=ChatCompletionMessage(content='<图片>这是一只可爱的猫, 毛色是条纹的,眼睛大而圆,显得十分好奇。它趴在一个木桌上,头微微歪向一侧,看起来很放松。背景模糊,给人一种温馨的感觉。</图片>', refusal=None, role='assistant', audio=None, function_call=None, tool_calls=None))], created=1739675512, model='gpt-4o-mini-2024-07-18', object='chat.completion', service_tier='default', system_fingerprint='fp_13eed4fce1', usage=CompletionUsage(completion_tokens=68, prompt_tokens=636, total_tokens=704, completion_tokens_details=CompletionTokensDetails(accepted_prediction_tokens=0, audio_tokens=0, reasoning_tokens=0, rejected_prediction_tokens=0), prompt_tokens_details=PromptTokensDetails(audio_tokens=0, cached_tokens=0)))
 [22:11:53| DEBUG] [long_term_memory.py:127]: ltm | aiocqhttp:FriendMessage:123456789 |  [Image: <图片>这是一只可爱的猫 ,毛色是条纹的,眼睛大而圆,显得十分好奇。它趴在一个木桌上,头微微歪向一侧,看起来很放松。背景模糊,给人一种温馨的感觉。</图片>]
 [22:11:53| DEBUG] [llm_request.py:80]: 提供商请求 Payload: ProviderRequest(prompt=You are now in a chatroom. The chat history is as follows:
 [Image: <图片>这是一只可爱的猫,毛色是条纹的,眼睛大而圆,显得十分好奇。它趴在一个木桌上,头微微歪向一侧,看起来很放松 。背景模糊,给人一种温馨的感觉。</图片>]
Now, a new message is coming: `
[User ID: 123456789, Nickname: 山里灵活的狗]
`. Please react to it. Only output your response and do not output any other information., session_id=af58d6c9-ca73-47fa-96dd-e88880ed3902, image_urls=['https://multimedia.nt.qq.com.cn/download?appid=1406&fileid=EhQfMUztr48Q1XrKbVBO-cPnEJ_DrRiLmBQg_gooxomDpJzHiwMyBHByb2RaEHwoXhC5GpLJADI0CiVOX3o&rkey=CAMSKMa3OFokB_TlMny3-PJX-KpSayWFw8sLPxVnc4PbiCjZw7Tsp2awMHk'], func_tool=[FuncTool(name='python_interpreter', parameters={'type': 'object', 'properties': {}}, description='Use this tool only if user really want to solve a complex problem and the problem can be solved very well by Python code. \nFor example, user can use this tool to solve math problems, edit image, docx, pptx, pdf, etc.', handler=functools.partial(<function Main.python_interpreter at 0x000001A9F908F7E0>, <packages.python_interpreter.main.Main object at 0x000001A9F8CBFD10>), handler_module_path='packages.python_interpreter.main', active=False), FuncTool(name='reminder', parameters={'type': 'object', 'properties': {'text': {'type': 'string', 'description': 'Must Required. The content of the reminder.'}, 'datetime_str': {'type': 'string', 'description': "Required when user's reminder is a single reminder. The datetime string of the reminder, Must format with %Y-%m-%d %H:%M"}, 'cron_expression': {'type': 'string', 'description': "Required when user's reminder is a repeated reminder. The cron expression of the reminder."}, 'human_readable_cron': {'type': 'string', 'description': 'Optional. The human readable cron expression of the reminder.'}}}, description='Call this function when user is asking for setting a reminder.\n', handler=functools.partial(<function Main.reminder_tool at 0x000001A9F9136FC0>, <packages.reminder.main.Main object at 0x000001A9F8DD4CB0>), handler_module_path='packages.reminder.main', active=True), FuncTool(name='web_search', parameters={'type': 'object', 'properties': {'query': {'type': 'string', 'description': "A search query which will be used to fetch the most relevant snippets regarding the user's query"}}}, description="Search the web for answers to the user's query\n", handler=functools.partial(<function Main.search_from_search_engine at 0x000001A9F95E3CE0>, <packages.web_searcher.main.Main object at 0x000001A9F9079010>), handler_module_path='packages.web_searcher.main', active=False), FuncTool(name='fetch_url', parameters={'type': 'object', 'properties': {'url': {'type': 'string', 'description': 'The url of the website to fetch content from'}}}, description='fetch the content of a website with the given web url\n', handler=functools.partial(<function Main.fetch_website_content at 0x000001A9F95E3D80>, <packages.web_searcher.main.Main object at 0x000001A9F9079010>), handler_module_path='packages.web_searcher.main', active=False)], contexts=[], system_prompt=
Current datetime: 2025-02-16 11:11
你将扮演亚托利(省略一大段系统提示词),私は、高性能ですから!
 [22:12:03| INFO] [openai_source.py:185]: ep-20250214075829-c4rhq 不支持函数工具调用,已自动去除,不影响使用。
 [22:12:08| ERROR] [llm_request.py:137]: Traceback (most recent call last):
  File "C:\Users\Admin\Downloads\AstrBotLauncher-0.1.5.5\AstrBot\astrbot\core\pipeline\process_stage\method\llm_request.py", line 83, in process
    llm_response = await provider.text_chat(**req.__dict__) # 请求 LLM
                   ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\Admin\Downloads\AstrBotLauncher-0.1.5.5\AstrBot\astrbot\core\provider\sources\openai_source.py", line 188, in text_chat
    llm_response = await self._query(payloads, None)
                   ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\Admin\Downloads\AstrBotLauncher-0.1.5.5\AstrBot\astrbot\core\provider\sources\openai_source.py", line 71, in _query
    completion = await self.client.chat.completions.create(
                 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\Admin\AppData\Local\Programs\Python\Python312\Lib\site-packages\openai\resources\chat\completions\completions.py", line 1927, in create
    return await self._post(
           ^^^^^^^^^^^^^^^^^
  File "C:\Users\Admin\AppData\Local\Programs\Python\Python312\Lib\site-packages\openai\_base_client.py", line 1856, in post
    return await self.request(cast_to, opts, stream=stream, stream_cls=stream_cls)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\Admin\AppData\Local\Programs\Python\Python312\Lib\site-packages\openai\_base_client.py", line 1550, in request
    return await self._request(
           ^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\Admin\AppData\Local\Programs\Python\Python312\Lib\site-packages\openai\_base_client.py", line 1651, in _request
    raise self._make_status_error_from_response(err.response) from None
openai.BadRequestError: Error code: 400 - {'error': {'code': 'InvalidParameter', 'message': 'One or more parameters specified in the request are not valid. Request id: 021739675524589409fb9fe586706ad74dc3a1dfc5d59ecf9094c', 'param': '', 'type': 'BadRequest'}}

你愿意提交 PR 吗?

  • [x] 是的,我愿意提交 PR!

Code of Conduct

  • [x] 我已阅读并同意遵守该项目的 行为准则。

Rt39 avatar Feb 16 '25 04:02 Rt39

你好,设计上来说私聊用不到图片转述,因为私聊场景下图片数量较少,可以直接放进上下文,没必要多进行一步转换的操作

Soulter avatar Feb 20 '25 14:02 Soulter

请问修改代码前如果不使用图片转述有这个报错吗

Soulter avatar Feb 20 '25 15:02 Soulter

没有这个报错,或许我应该把它改成[Feature]标签,让非VLM的模型(例如deepseek)获得其他模型对图片的转述

Rt39 avatar Feb 20 '25 23:02 Rt39

看报错说是请求时包含了不合法的参数,可以输出 llm_response = await self._query(payloads, None) 中的 payloads 看看?

另外,目前已经支持了自定义图片转述的模型:

Image

Soulter avatar Feb 24 '25 17:02 Soulter

模型提供商里面并没有火山引擎的,请问能告诉我怎么接入火山引擎DeepSeekR1的API吗

Tianbawen avatar Feb 27 '25 14:02 Tianbawen

用openai的供应商,是兼容的

Rt39 avatar Feb 28 '25 04:02 Rt39

同样,调用deepseek的模型和开启图像转述功能后(用了gpt-4o-mini)。也是报错。目前不知道解决办法

Zawinzala avatar Mar 17 '25 11:03 Zawinzala

这个功能已经在 #2422 中被实现。请等待 v4.0.0 发布。

Soulter avatar Aug 14 '25 06:08 Soulter