Skip to content

CubeLoop — a Pythonic, async-native agent harness core designed for high performance, readability, and production-grade persistence.

feat(providers): apply sender attribution at provider boundary

xf gongba341ae19cb0
diff --git a/cubepi/providers/anthropic.py b/cubepi/providers/anthropic.py
index 2b8ab39..f5cb04f 100644
--- a/cubepi/providers/anthropic.py
+++ b/cubepi/providers/anthropic.py
@@ -25,6 +25,7 @@ from cubepi.providers.base import (
UserMessage,
_fire_request_listeners,
_fire_response_listeners,
+ apply_sender_attribution,
invoke_on_payload,
invoke_on_response,
)
@@ -494,7 +495,8 @@ class AnthropicProvider(BaseProvider):
def _convert_message(msg: Message) -> dict[str, Any]:
if isinstance(msg, UserMessage):
user_content: list[dict[str, Any]] = []
- for user_block in msg.content:
+ attributed = apply_sender_attribution(msg, msg.content)
+ for user_block in attributed:
if isinstance(user_block, TextContent):
user_content.append({"type": "text", "text": user_block.text})
elif isinstance(user_block, ImageContent):
diff --git a/cubepi/providers/base.py b/cubepi/providers/base.py
index 5963098..9c27a65 100644
--- a/cubepi/providers/base.py
+++ b/cubepi/providers/base.py
@@ -199,6 +199,58 @@ def is_synthetic_message(message: Message) -> bool:
return message.metadata.get(SYNTHETIC_METADATA_KEY) is True
+# --- Sender attribution (group chat) ---
+#
+# When multiple humans share one conversation, each user message carries
+# the sender's display name in metadata. Providers render the prefix at
+# call-time rather than callers mutating ``content`` at write-time. This
+# keeps stored messages clean (frontend can show sender via avatar/badge
+# without stripping a prefix), handles attachment-only messages correctly,
+# and concentrates the formatting in one place.
+
+SENDER_DISPLAY_NAME_METADATA_KEY = "sender_display_name"
+SENDER_USER_ID_METADATA_KEY = "sender_user_id"
+
+
+def get_sender_display_name(message: Message) -> str | None:
+ """Return the sender's display name, or None for non-attributed messages."""
+ value = message.metadata.get(SENDER_DISPLAY_NAME_METADATA_KEY)
+ return value if isinstance(value, str) and value else None
+
+
+def apply_sender_attribution(
+ message: UserMessage, content: list[Content]
+) -> list[Content]:
+ """Prefix the first non-empty text block with ``[name]: ``.
+
+ Returns a new list — the original ``content`` is not mutated. If the
+ message has no sender metadata, returns ``content`` unchanged. If the
+ message has sender metadata but no text content (attachment-only),
+ prepends a synthetic text block so the model still knows who sent
+ the attachments.
+ """
+ display_name = get_sender_display_name(message)
+ if not display_name:
+ return content
+
+ prefix = f"[{display_name}]: "
+ out: list[Content] = []
+ applied = False
+ for block in content:
+ if not applied and isinstance(block, TextContent) and block.text:
+ out.append(TextContent(text=prefix + block.text))
+ applied = True
+ else:
+ out.append(block)
+
+ if not applied:
+ # Attachment-only or empty text — prepend a sender announcement so
+ # the agent doesn't see a faceless attachment list in a group chat.
+ out.insert(0, TextContent(text=f"[{display_name}] sent:"))
+
+ return out
+
+
class ToolDefinition(BaseModel):
name: str
description: str
diff --git a/cubepi/providers/openai.py b/cubepi/providers/openai.py
index f5883dd..3c45eee 100644
--- a/cubepi/providers/openai.py
+++ b/cubepi/providers/openai.py
@@ -33,6 +33,7 @@ from cubepi.providers.base import (
UserMessage,
_fire_request_listeners,
_fire_response_listeners,
+ apply_sender_attribution,
invoke_on_payload,
invoke_on_response,
)
@@ -630,10 +631,11 @@ class OpenAIProvider(BaseProvider):
@staticmethod
def _convert_message(msg: Message) -> dict[str, Any]:
if isinstance(msg, UserMessage):
- has_image = any(isinstance(c, ImageContent) for c in msg.content)
+ attributed = apply_sender_attribution(msg, msg.content)
+ has_image = any(isinstance(c, ImageContent) for c in attributed)
if has_image:
parts: list[dict[str, Any]] = []
- for c in msg.content:
+ for c in attributed:
if isinstance(c, TextContent):
parts.append({"type": "text", "text": c.text})
elif isinstance(c, ImageContent):
@@ -646,7 +648,7 @@ class OpenAIProvider(BaseProvider):
}
)
return {"role": "user", "content": parts}
- text_parts = [c.text for c in msg.content if isinstance(c, TextContent)]
+ text_parts = [c.text for c in attributed if isinstance(c, TextContent)]
return {"role": "user", "content": "\n".join(text_parts)}
elif isinstance(msg, AssistantMessage):
diff --git a/cubepi/providers/openai_responses.py b/cubepi/providers/openai_responses.py
index 43100a6..5aa5a8e 100644
--- a/cubepi/providers/openai_responses.py
+++ b/cubepi/providers/openai_responses.py
@@ -26,6 +26,7 @@ from cubepi.providers.base import (
UserMessage,
_fire_request_listeners,
_fire_response_listeners,
+ apply_sender_attribution,
invoke_on_payload,
invoke_on_response,
)
@@ -649,7 +650,8 @@ class OpenAIResponsesProvider(BaseProvider):
for msg in messages:
if isinstance(msg, UserMessage):
content: list[dict[str, Any]] = []
- for c in msg.content:
+ attributed = apply_sender_attribution(msg, msg.content)
+ for c in attributed:
if isinstance(c, TextContent):
content.append({"type": "input_text", "text": c.text})
elif isinstance(c, ImageContent):
diff --git a/tests/providers/test_sender_attribution.py b/tests/providers/test_sender_attribution.py
new file mode 100644
index 0000000..1903b49
--- /dev/null
+++ b/tests/providers/test_sender_attribution.py
@@ -0,0 +1,116 @@
+"""Tests for sender_attribution helpers used by group chat."""
+
+from cubepi.providers.base import (
+ ImageContent,
+ TextContent,
+ UserMessage,
+ apply_sender_attribution,
+ get_sender_display_name,
+)
+
+
+class TestGetSenderDisplayName:
+ def test_returns_name_when_present(self):
+ msg = UserMessage(
+ content=[TextContent(text="hi")],
+ metadata={"sender_display_name": "Alice"},
+ )
+ assert get_sender_display_name(msg) == "Alice"
+
+ def test_returns_none_when_missing(self):
+ msg = UserMessage(content=[TextContent(text="hi")])
+ assert get_sender_display_name(msg) is None
+
+ def test_returns_none_for_empty_string(self):
+ msg = UserMessage(
+ content=[TextContent(text="hi")],
+ metadata={"sender_display_name": ""},
+ )
+ assert get_sender_display_name(msg) is None
+
+ def test_returns_none_for_non_string(self):
+ msg = UserMessage(
+ content=[TextContent(text="hi")],
+ metadata={"sender_display_name": 42},
+ )
+ assert get_sender_display_name(msg) is None
+
+
+class TestApplySenderAttribution:
+ def test_no_metadata_returns_content_unchanged(self):
+ msg = UserMessage(content=[TextContent(text="hi")])
+ out = apply_sender_attribution(msg, msg.content)
+ assert out == msg.content
+
+ def test_prefixes_first_text_block(self):
+ msg = UserMessage(
+ content=[TextContent(text="hello world")],
+ metadata={"sender_display_name": "Alice"},
+ )
+ out = apply_sender_attribution(msg, msg.content)
+ assert len(out) == 1
+ assert isinstance(out[0], TextContent)
+ assert out[0].text == "[Alice]: hello world"
+
+ def test_only_first_text_block_gets_prefix(self):
+ msg = UserMessage(
+ content=[
+ TextContent(text="first"),
+ TextContent(text="second"),
+ ],
+ metadata={"sender_display_name": "Alice"},
+ )
+ out = apply_sender_attribution(msg, msg.content)
+ assert isinstance(out[0], TextContent)
+ assert isinstance(out[1], TextContent)
+ assert out[0].text == "[Alice]: first"
+ assert out[1].text == "second"
+
+ def test_skips_empty_text_block_when_prefixing(self):
+ msg = UserMessage(
+ content=[
+ TextContent(text=""),
+ TextContent(text="real content"),
+ ],
+ metadata={"sender_display_name": "Alice"},
+ )
+ out = apply_sender_attribution(msg, msg.content)
+ assert isinstance(out[0], TextContent)
+ assert isinstance(out[1], TextContent)
+ assert out[0].text == ""
+ assert out[1].text == "[Alice]: real content"
+
+ def test_attachment_only_message_gets_synthetic_prefix(self):
+ msg = UserMessage(
+ content=[
+ ImageContent(media_type="image/png", source="base64data"),
+ ],
+ metadata={"sender_display_name": "Alice"},
+ )
+ out = apply_sender_attribution(msg, msg.content)
+ assert len(out) == 2
+ assert isinstance(out[0], TextContent)
+ assert out[0].text == "[Alice] sent:"
+ assert isinstance(out[1], ImageContent)
+
+ def test_does_not_mutate_input(self):
+ msg = UserMessage(
+ content=[TextContent(text="hi")],
+ metadata={"sender_display_name": "Alice"},
+ )
+ original_text = msg.content[0].text
+ apply_sender_attribution(msg, msg.content)
+ assert msg.content[0].text == original_text
+
+ def test_mixed_text_and_image_only_text_prefixed(self):
+ msg = UserMessage(
+ content=[
+ TextContent(text="look at this"),
+ ImageContent(media_type="image/png", source="base64data"),
+ ],
+ metadata={"sender_display_name": "Alice"},
+ )
+ out = apply_sender_attribution(msg, msg.content)
+ assert isinstance(out[0], TextContent)
+ assert out[0].text == "[Alice]: look at this"
+ assert isinstance(out[1], ImageContent)