add images support

This commit is contained in:
timka123 committed 2026-11-23 18:19:24 +03:00
1 parent 2b3518f873
commit d972f4b314
14 files changed
+2157 -51

No files matched your search

+104 -3
View File
@@ -8,6 +8,13 @@ from typing import Any, Awaitable, Callable, Optional
import openai
from openai import AsyncOpenAI
from homeagent.agent.attachments import (
OPENAI_IMAGE_MIMES,
Attachment,
build_history_user_text,
format_inline_text_attachments,
stage_attachments_in_sandbox,
)
from homeagent.agent.base import BaseAgent
from homeagent.agent.conversation import ConversationManager
from homeagent.config import Settings, get_settings
@@ -71,6 +78,93 @@ class OpenAIAgent(BaseAgent):
return "\n\n".join(parts)
def _build_user_turn(
self,
user_message: str,
attachments: list[Attachment],
) -> dict[str, Any]:
"""Build an OpenAI/DeepSeek user message payload supporting images, PDFs, audio, and text files."""
if not attachments:
return {"role": "user", "content": user_message}
inline_text, binary_attachments = format_inline_text_attachments(attachments)
text_sections: list[str] = []
if inline_text:
text_sections.append(inline_text)
multimodal_blocks: list[dict[str, Any]] = []
notes: list[str] = []
if self.provider == "deepseek":
# DeepSeek Chat Completions API is text-only; avoid sending image_url/file blocks that return HTTP 400
for att in binary_attachments:
sandbox_hint = (
f" Файл сохранён в песочнице: `{att.sandbox_path}` — при необходимости можно обработать его через `code_execute`."
if att.sandbox_path
else ""
)
notes.append(
f"- Бинарное вложение {att.to_summary_line()} (активный провайдер DeepSeek текстовый и не принимает "
f"изображения/PDF/аудио напрямую; для анализа картинок переключитесь на Gemini, OpenAI или Antigravity).{sandbox_hint}"
)
else:
for att in binary_attachments:
mime = att.mime_type.lower()
if mime in OPENAI_IMAGE_MIMES:
multimodal_blocks.append(
{
"type": "image_url",
"image_url": {"url": f"data:{mime};base64,{att.base64_data()}"},
}
)
notes.append(f"- Прикреплено изображение: {att.to_summary_line()}")
elif att.is_pdf:
multimodal_blocks.append(
{
"type": "file",
"file": {
"filename": att.filename,
"file_data": f"data:application/pdf;base64,{att.base64_data()}",
},
}
)
notes.append(f"- Прикреплён PDF-документ: {att.to_summary_line()}")
elif mime in ("audio/wav", "audio/x-wav", "audio/mpeg", "audio/mp3"):
audio_fmt = "wav" if "wav" in mime else "mp3"
multimodal_blocks.append(
{
"type": "input_audio",
"input_audio": {
"data": att.base64_data(),
"format": audio_fmt,
},
}
)
notes.append(f"- Прикреплено аудио: {att.to_summary_line()}")
else:
sandbox_hint = (
f" Файл сохранён в песочнице: `{att.sandbox_path}` (можно обработать через `code_execute`)."
if att.sandbox_path
else ""
)
notes.append(
f"- Вложение `{att.filename}` ({att.mime_type}, {att.human_size}) не поддерживается напрямую "
f"форматом OpenAI Chat Completions.{sandbox_hint}"
)
if notes:
text_sections.append("[Вложения пользователя]:\n" + "\n".join(notes))
if user_message.strip():
text_sections.append(user_message)
combined_text = "\n\n".join(text_sections) or user_message
if multimodal_blocks:
return {
"role": "user",
"content": [{"type": "text", "text": combined_text}, *multimodal_blocks],
}
return {"role": "user", "content": combined_text}
async def chat(
self,
chat_id: int,
@@ -78,6 +172,7 @@ class OpenAIAgent(BaseAgent):
user_message: str,
max_tool_iterations: int = 100,
on_progress: Optional[Callable[[str], Awaitable[None]]] = None,
attachments: Optional[list[Attachment]] = None,
) -> str:
"""Process user message within topic context using DeepSeek / OpenAI API."""
if not self._client:
@@ -107,8 +202,9 @@ class OpenAIAgent(BaseAgent):
# 1. Fetch current conversation history
history = list(self.conversation_manager.get_openai_messages(chat_id, thread_id))
# 2. Add current user message
user_turn: dict[str, Any] = {"role": "user", "content": user_message}
# 2. Stage attachments and build current user message
staged_attachments = stage_attachments_in_sandbox(attachments, self.settings)
user_turn = self._build_user_turn(user_message, staged_attachments)
history.append(user_turn)
system_instruction = self._build_system_instruction()
@@ -117,7 +213,12 @@ class OpenAIAgent(BaseAgent):
*history,
]
turn_sequence: list[dict[str, Any]] = [user_turn]
# Persist compact text-only turn representation (avoid storing megabyte base64 payloads in session JSON)
history_user_turn: dict[str, Any] = {
"role": "user",
"content": build_history_user_text(user_message, staged_attachments),
}
turn_sequence: list[dict[str, Any]] = [history_user_turn]
tools = self.registry.get_openai_tools()
for iteration in range(max_tool_iterations):