Skip to content

Commit 1ba8b48

Browse files
committed
Improve ProxyAgent clarification and message handling
Enhanced ProxyAgent to provide more informative logging, generate consistent response and message IDs, and yield explicit text and usage updates for clarification requests. Updated message extraction to use the .text property of ChatMessage for accurate content retrieval. Also fixed agent_response_callback to properly extract text from ChatMessage objects.
1 parent c10c3ec commit 1ba8b48

File tree

3 files changed

+60
-13
lines changed

3 files changed

+60
-13
lines changed

src/backend/v4/callbacks/response_handlers.py

Lines changed: 11 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -75,7 +75,17 @@ def agent_response_callback(
7575
"""
7676
agent_name = getattr(message, "author_name", None) or agent_id or "Unknown Agent"
7777
role = getattr(message, "role", "assistant")
78-
text = clean_citations(getattr(message, "text", "") or "")
78+
79+
# FIX: Properly extract text from ChatMessage
80+
# ChatMessage has a .text property that concatenates all TextContent items
81+
text = ""
82+
if isinstance(message, ChatMessage):
83+
text = message.text # Use the property directly
84+
else:
85+
# Fallback for non-ChatMessage objects
86+
text = str(getattr(message, "text", ""))
87+
88+
text = clean_citations(text or "")
7989

8090
if not user_id:
8191
logger.debug("No user_id provided; skipping websocket send for final message.")
@@ -98,7 +108,6 @@ def agent_response_callback(
98108
except Exception as e:
99109
logger.error("agent_response_callback error sending WebSocket message: %s", e)
100110

101-
102111
async def streaming_agent_response_callback(
103112
agent_id: str,
104113
update: AgentRunResponseUpdate,

src/backend/v4/magentic_agents/foundry_agent.py

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -131,7 +131,6 @@ async def invoke(self, prompt: str):
131131
async for update in self._agent.run_stream(messages=messages):
132132
yield update
133133

134-
135134
# -------------------------
136135
# Factory
137136
# -------------------------

src/backend/v4/magentic_agents/proxy_agent.py

Lines changed: 49 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -69,6 +69,19 @@ def __init__(
6969
# AgentProtocol implementation
7070
# ---------------------------
7171

72+
def get_new_thread(self, **kwargs: Any) -> AgentThread:
73+
"""
74+
Create a new thread for ProxyAgent conversations.
75+
Required by AgentProtocol for workflow integration.
76+
77+
Args:
78+
**kwargs: Additional keyword arguments for thread creation
79+
80+
Returns:
81+
A new AgentThread instance
82+
"""
83+
return AgentThread(**kwargs)
84+
7285
async def run(
7386
self,
7487
messages: str | ChatMessage | list[str] | list[ChatMessage] | None = None,
@@ -141,6 +154,13 @@ async def _invoke_stream_internal(
141154
# Normalize messages to string
142155
message_text = self._extract_message_text(messages)
143156

157+
logger.info(
158+
"ProxyAgent: Requesting clarification (thread=%s, user=%s)",
159+
"present" if thread else "None",
160+
self.user_id
161+
)
162+
logger.debug("ProxyAgent: Message text: %s", message_text[:100])
163+
144164
clarification_req_text = f"I need clarification about: {message_text}"
145165
clarification_request = UserClarificationRequest(
146166
question=clarification_req_text,
@@ -174,33 +194,50 @@ async def _invoke_stream_internal(
174194
if human_response.answer
175195
else "No additional clarification provided."
176196
)
177-
synthetic_reply = f"Human clarification: {answer_text}"
197+
198+
# Return just the user's answer directly - no prefix that might confuse orchestrator
199+
synthetic_reply = answer_text
200+
201+
logger.info("ProxyAgent: Received clarification: %s", synthetic_reply[:100])
178202

179-
# Yield final assistant text update
180-
yield AgentRunResponseUpdate(
203+
# Generate consistent IDs for this response
204+
response_id = str(uuid.uuid4())
205+
message_id = str(uuid.uuid4())
206+
207+
# Yield final assistant text update with explicit text content
208+
text_update = AgentRunResponseUpdate(
181209
role=Role.ASSISTANT,
182210
contents=[TextContent(text=synthetic_reply)],
183211
author_name=self.name,
184-
response_id=str(uuid.uuid4()),
185-
message_id=str(uuid.uuid4()),
212+
response_id=response_id,
213+
message_id=message_id,
186214
)
215+
216+
logger.debug("ProxyAgent: Yielding text update (text length=%d)", len(synthetic_reply))
217+
yield text_update
187218

188219
# Yield synthetic usage update for consistency
189-
yield AgentRunResponseUpdate(
220+
# Use same message_id to indicate this is part of the same message
221+
usage_update = AgentRunResponseUpdate(
190222
role=Role.ASSISTANT,
191223
contents=[
192224
UsageContent(
193225
UsageDetails(
194-
input_token_count=0,
226+
input_token_count=len(message_text.split()),
195227
output_token_count=len(synthetic_reply.split()),
196-
total_token_count=len(synthetic_reply.split()),
228+
total_token_count=len(message_text.split()) + len(synthetic_reply.split()),
197229
)
198230
)
199231
],
200232
author_name=self.name,
201-
response_id=str(uuid.uuid4()),
202-
message_id=str(uuid.uuid4()),
233+
response_id=response_id,
234+
message_id=message_id, # Same message_id groups with text content
203235
)
236+
237+
logger.debug("ProxyAgent: Yielding usage update")
238+
yield usage_update
239+
240+
logger.info("ProxyAgent: Completed clarification response")
204241

205242
# ---------------------------
206243
# Helper methods
@@ -215,13 +252,15 @@ def _extract_message_text(
215252
if isinstance(messages, str):
216253
return messages
217254
if isinstance(messages, ChatMessage):
255+
# Use the .text property which concatenates all TextContent items
218256
return messages.text or ""
219257
if isinstance(messages, list):
220258
if not messages:
221259
return ""
222260
if isinstance(messages[0], str):
223261
return " ".join(messages)
224262
if isinstance(messages[0], ChatMessage):
263+
# Use .text property for each message
225264
return " ".join(msg.text or "" for msg in messages)
226265
return str(messages)
227266

0 commit comments

Comments
 (0)