Spaces:
Sleeping
Sleeping
Add file attachments to chat input
Browse files- ui/chat.py +7 -0
- ui/inference/messages.py +106 -5
- ui/inference/respond.py +9 -4
ui/chat.py
CHANGED
|
@@ -56,6 +56,13 @@ def create_chat_interface(
|
|
| 56 |
"""
|
| 57 |
return SidebarChatInterface(
|
| 58 |
respond,
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 59 |
history_container=history_container,
|
| 60 |
additional_inputs=ADDITIONAL_INPUTS,
|
| 61 |
)
|
|
|
|
| 56 |
"""
|
| 57 |
return SidebarChatInterface(
|
| 58 |
respond,
|
| 59 |
+
multimodal=True,
|
| 60 |
+
textbox=gr.MultimodalTextbox(
|
| 61 |
+
show_label=False,
|
| 62 |
+
placeholder="Enter message or upload file...",
|
| 63 |
+
file_count="multiple",
|
| 64 |
+
sources=["upload"],
|
| 65 |
+
),
|
| 66 |
history_container=history_container,
|
| 67 |
additional_inputs=ADDITIONAL_INPUTS,
|
| 68 |
)
|
ui/inference/messages.py
CHANGED
|
@@ -1,9 +1,12 @@
|
|
| 1 |
# ui/inference/messages.py
|
| 2 |
from __future__ import annotations
|
| 3 |
|
|
|
|
| 4 |
import json
|
|
|
|
| 5 |
import re
|
| 6 |
import uuid
|
|
|
|
| 7 |
from typing import Any
|
| 8 |
|
| 9 |
from .config import TOOLS
|
|
@@ -11,17 +14,115 @@ from .config import TOOLS
|
|
| 11 |
|
| 12 |
TOOL_NAMES = {tool["function"]["name"] for tool in TOOLS}
|
| 13 |
|
|
|
|
| 14 |
|
| 15 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 16 |
"""Convert Gradio chat history to API messages, skipping UI-only tool steps."""
|
| 17 |
-
messages: list[dict[str,
|
| 18 |
for msg in history:
|
| 19 |
if msg.get("metadata"):
|
| 20 |
continue
|
| 21 |
-
content = msg.get("content")
|
| 22 |
role = msg.get("role")
|
| 23 |
-
if role in ("user", "assistant")
|
| 24 |
-
|
|
|
|
|
|
|
|
|
|
| 25 |
return messages
|
| 26 |
|
| 27 |
|
|
|
|
| 1 |
# ui/inference/messages.py
|
| 2 |
from __future__ import annotations
|
| 3 |
|
| 4 |
+
import base64
|
| 5 |
import json
|
| 6 |
+
import mimetypes
|
| 7 |
import re
|
| 8 |
import uuid
|
| 9 |
+
from pathlib import Path
|
| 10 |
from typing import Any
|
| 11 |
|
| 12 |
from .config import TOOLS
|
|
|
|
| 14 |
|
| 15 |
TOOL_NAMES = {tool["function"]["name"] for tool in TOOLS}
|
| 16 |
|
| 17 |
+
TEXT_FILE_SUFFIXES = (".txt", ".md", ".csv", ".json", ".xml", ".html", ".htm")
|
| 18 |
|
| 19 |
+
|
| 20 |
+
def _file_path(item: Any) -> str | None:
|
| 21 |
+
if isinstance(item, str):
|
| 22 |
+
return item
|
| 23 |
+
if isinstance(item, dict):
|
| 24 |
+
if "path" in item:
|
| 25 |
+
return item["path"]
|
| 26 |
+
if item.get("type") == "file":
|
| 27 |
+
file_data = item.get("file") or {}
|
| 28 |
+
return file_data.get("path") or file_data.get("url")
|
| 29 |
+
return None
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
def _text_content(item: Any) -> str | None:
|
| 33 |
+
if isinstance(item, str):
|
| 34 |
+
return item
|
| 35 |
+
if isinstance(item, dict) and item.get("type") == "text":
|
| 36 |
+
return item.get("text") or ""
|
| 37 |
+
return None
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
def _file_to_api_part(path: str) -> dict[str, Any]:
|
| 41 |
+
mime_type, _ = mimetypes.guess_type(path)
|
| 42 |
+
mime_type = mime_type or "application/octet-stream"
|
| 43 |
+
name = Path(path).name
|
| 44 |
+
|
| 45 |
+
if mime_type.startswith("image/"):
|
| 46 |
+
data = Path(path).read_bytes()
|
| 47 |
+
encoded = base64.b64encode(data).decode("utf-8")
|
| 48 |
+
return {
|
| 49 |
+
"type": "image_url",
|
| 50 |
+
"image_url": {"url": f"data:{mime_type};base64,{encoded}"},
|
| 51 |
+
}
|
| 52 |
+
|
| 53 |
+
if mime_type.startswith("text/") or path.lower().endswith(TEXT_FILE_SUFFIXES):
|
| 54 |
+
try:
|
| 55 |
+
text = Path(path).read_text(encoding="utf-8", errors="replace")
|
| 56 |
+
return {"type": "text", "text": f"[File: {name}]\n{text}"}
|
| 57 |
+
except OSError:
|
| 58 |
+
pass
|
| 59 |
+
|
| 60 |
+
return {"type": "text", "text": f"[Attached file: {name}]"}
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
def _parts_to_api_content(parts: list[dict[str, Any]]) -> str | list[dict[str, Any]]:
|
| 64 |
+
if not parts:
|
| 65 |
+
return ""
|
| 66 |
+
if len(parts) == 1 and parts[0]["type"] == "text":
|
| 67 |
+
return parts[0]["text"]
|
| 68 |
+
return parts
|
| 69 |
+
|
| 70 |
+
|
| 71 |
+
def multimodal_input_to_api_content(
|
| 72 |
+
message: str | dict[str, Any],
|
| 73 |
+
) -> str | list[dict[str, Any]]:
|
| 74 |
+
"""Convert a ChatInterface user message to Inference API content."""
|
| 75 |
+
if isinstance(message, str):
|
| 76 |
+
return message
|
| 77 |
+
|
| 78 |
+
parts: list[dict[str, Any]] = []
|
| 79 |
+
for file_ref in message.get("files") or []:
|
| 80 |
+
path = _file_path(file_ref) if isinstance(file_ref, dict) else file_ref
|
| 81 |
+
if path:
|
| 82 |
+
parts.append(_file_to_api_part(path))
|
| 83 |
+
|
| 84 |
+
text = (message.get("text") or "").strip()
|
| 85 |
+
if text:
|
| 86 |
+
parts.append({"type": "text", "text": text})
|
| 87 |
+
|
| 88 |
+
return _parts_to_api_content(parts)
|
| 89 |
+
|
| 90 |
+
|
| 91 |
+
def chat_content_to_api(content: Any) -> str | list[dict[str, Any]] | None:
|
| 92 |
+
"""Convert Gradio chat history content to Inference API content."""
|
| 93 |
+
if isinstance(content, str):
|
| 94 |
+
return content or None
|
| 95 |
+
|
| 96 |
+
if not isinstance(content, list):
|
| 97 |
+
return None
|
| 98 |
+
|
| 99 |
+
parts: list[dict[str, Any]] = []
|
| 100 |
+
for item in content:
|
| 101 |
+
text = _text_content(item)
|
| 102 |
+
if text:
|
| 103 |
+
parts.append({"type": "text", "text": text})
|
| 104 |
+
continue
|
| 105 |
+
path = _file_path(item)
|
| 106 |
+
if path:
|
| 107 |
+
parts.append(_file_to_api_part(path))
|
| 108 |
+
|
| 109 |
+
if not parts:
|
| 110 |
+
return None
|
| 111 |
+
return _parts_to_api_content(parts)
|
| 112 |
+
|
| 113 |
+
|
| 114 |
+
def history_to_api_messages(history: list[dict[str, Any]]) -> list[dict[str, Any]]:
|
| 115 |
"""Convert Gradio chat history to API messages, skipping UI-only tool steps."""
|
| 116 |
+
messages: list[dict[str, Any]] = []
|
| 117 |
for msg in history:
|
| 118 |
if msg.get("metadata"):
|
| 119 |
continue
|
|
|
|
| 120 |
role = msg.get("role")
|
| 121 |
+
if role not in ("user", "assistant"):
|
| 122 |
+
continue
|
| 123 |
+
api_content = chat_content_to_api(msg.get("content"))
|
| 124 |
+
if api_content:
|
| 125 |
+
messages.append({"role": role, "content": api_content})
|
| 126 |
return messages
|
| 127 |
|
| 128 |
|
ui/inference/respond.py
CHANGED
|
@@ -9,14 +9,14 @@ from huggingface_hub import InferenceClient
|
|
| 9 |
|
| 10 |
from .completion import complete_turn
|
| 11 |
from .config import MAX_TOOL_ROUNDS, MODEL_ID, TOOLS
|
| 12 |
-
from .messages import history_to_api_messages
|
| 13 |
from .streaming import yield_response
|
| 14 |
from .tools import execute_tool_calls
|
| 15 |
|
| 16 |
|
| 17 |
def respond(
|
| 18 |
-
message,
|
| 19 |
-
history: list[dict[str,
|
| 20 |
system_message,
|
| 21 |
max_tokens,
|
| 22 |
temperature,
|
|
@@ -28,10 +28,15 @@ def respond(
|
|
| 28 |
"""
|
| 29 |
client = InferenceClient(token=hf_token.token, model=MODEL_ID)
|
| 30 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 31 |
api_messages: list[dict[str, Any]] = [
|
| 32 |
{"role": "system", "content": system_message},
|
| 33 |
*history_to_api_messages(history),
|
| 34 |
-
{"role": "user", "content":
|
| 35 |
]
|
| 36 |
ui_messages: list[ChatMessage] = []
|
| 37 |
|
|
|
|
| 9 |
|
| 10 |
from .completion import complete_turn
|
| 11 |
from .config import MAX_TOOL_ROUNDS, MODEL_ID, TOOLS
|
| 12 |
+
from .messages import history_to_api_messages, multimodal_input_to_api_content
|
| 13 |
from .streaming import yield_response
|
| 14 |
from .tools import execute_tool_calls
|
| 15 |
|
| 16 |
|
| 17 |
def respond(
|
| 18 |
+
message: str | dict[str, Any],
|
| 19 |
+
history: list[dict[str, Any]],
|
| 20 |
system_message,
|
| 21 |
max_tokens,
|
| 22 |
temperature,
|
|
|
|
| 28 |
"""
|
| 29 |
client = InferenceClient(token=hf_token.token, model=MODEL_ID)
|
| 30 |
|
| 31 |
+
user_content = multimodal_input_to_api_content(message)
|
| 32 |
+
if not user_content:
|
| 33 |
+
yield from yield_response([], "Please enter a message or attach a file.")
|
| 34 |
+
return
|
| 35 |
+
|
| 36 |
api_messages: list[dict[str, Any]] = [
|
| 37 |
{"role": "system", "content": system_message},
|
| 38 |
*history_to_api_messages(history),
|
| 39 |
+
{"role": "user", "content": user_content},
|
| 40 |
]
|
| 41 |
ui_messages: list[ChatMessage] = []
|
| 42 |
|