-
Notifications
You must be signed in to change notification settings - Fork 1.3k
Expand file tree
/
Copy path_mapper.py
More file actions
1948 lines (1660 loc) · 86.1 KB
/
_mapper.py
File metadata and controls
1948 lines (1660 loc) · 86.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# Copyright (c) Microsoft. All rights reserved.
"""Agent Framework message mapper implementation."""
import json
import logging
import time
import uuid
from collections import OrderedDict
from collections.abc import Sequence
from datetime import datetime
from typing import Any, Union
from uuid import uuid4
from openai.types.responses import (
Response,
ResponseContentPartAddedEvent,
ResponseCreatedEvent,
ResponseError,
ResponseFailedEvent,
ResponseInProgressEvent,
)
from .models import (
AgentFrameworkRequest,
CustomResponseOutputItemAddedEvent,
CustomResponseOutputItemDoneEvent,
ExecutorActionItem,
InputTokensDetails,
OpenAIResponse,
OutputTokensDetails,
ResponseErrorEvent,
ResponseFunctionCallArgumentsDeltaEvent,
ResponseFunctionResultComplete,
ResponseFunctionToolCall,
ResponseOutputData,
ResponseOutputFile,
ResponseOutputImage,
ResponseOutputItemAddedEvent,
ResponseOutputMessage,
ResponseOutputText,
ResponseReasoningTextDeltaEvent,
ResponseStreamEvent,
ResponseTextDeltaEvent,
ResponseTraceEventComplete,
ResponseUsage,
ResponseWorkflowEventComplete,
)
logger = logging.getLogger(__name__)
# Type alias for all possible event types
EventType = Union[
ResponseStreamEvent,
ResponseWorkflowEventComplete,
ResponseOutputItemAddedEvent,
ResponseTraceEventComplete,
]
def _serialize_content_recursive(value: Any) -> Any:
"""Recursively serialize Agent Framework Content objects to JSON-compatible values.
This handles nested Content objects (like TextContent inside FunctionResultContent.result)
that can't be directly serialized by json.dumps().
Args:
value: Value to serialize (can be Content object, dict, list, primitive, etc.)
Returns:
JSON-serializable version with all Content objects converted to dicts/primitives
"""
# Handle None and basic JSON-serializable types
if value is None or isinstance(value, (str, int, float, bool)):
return value
# Check if it's a SerializationMixin (includes all Content types)
# Content objects have to_dict() method
if hasattr(value, "to_dict") and callable(getattr(value, "to_dict", None)):
try:
return value.to_dict()
except Exception as e:
# If to_dict() fails, fall through to other methods
logger.debug(f"Failed to serialize with to_dict(): {e}")
# Handle dictionaries - recursively process values
if isinstance(value, dict):
return {key: _serialize_content_recursive(val) for key, val in value.items()}
# Handle lists and tuples - recursively process elements
if isinstance(value, (list, tuple)):
serialized = [_serialize_content_recursive(item) for item in value]
# For single-item lists containing text Content, extract just the text
# This handles the MCP case where result = [TextContent(text="Hello")]
# and we want output = "Hello" not output = '[{"type": "text", "text": "Hello"}]'
if len(serialized) == 1 and isinstance(serialized[0], dict) and serialized[0].get("type") == "text":
return serialized[0].get("text", "")
return serialized
# For other objects with model_dump(), try that
if hasattr(value, "model_dump") and callable(getattr(value, "model_dump", None)):
try:
return value.model_dump()
except Exception as e:
logger.debug(f"Failed to serialize with model_dump(): {e}")
# Return as-is and let json.dumps handle it (may raise TypeError for non-serializable types)
return value
class MessageMapper:
"""Maps Agent Framework messages/responses to OpenAI format."""
def __init__(self, max_contexts: int = 1000) -> None:
"""Initialize Agent Framework message mapper.
Args:
max_contexts: Maximum number of contexts to keep in memory (default: 1000)
"""
self.sequence_counter = 0
self._conversion_contexts: OrderedDict[int, dict[str, Any]] = OrderedDict()
self._max_contexts = max_contexts
# Track usage per request for final Response.usage (OpenAI standard)
self._usage_accumulator: dict[str, dict[str, int]] = {}
# Register content type mappers for all 12 Agent Framework content types
self.content_mappers = {
"TextContent": self._map_text_content,
"TextReasoningContent": self._map_reasoning_content,
"FunctionCallContent": self._map_function_call_content,
"FunctionResultContent": self._map_function_result_content,
"ErrorContent": self._map_error_content,
"UsageContent": self._map_usage_content,
"DataContent": self._map_data_content,
"UriContent": self._map_uri_content,
"HostedFileContent": self._map_hosted_file_content,
"HostedVectorStoreContent": self._map_hosted_vector_store_content,
"FunctionApprovalRequestContent": self._map_approval_request_content,
"FunctionApprovalResponseContent": self._map_approval_response_content,
}
async def convert_event(self, raw_event: Any, request: AgentFrameworkRequest) -> Sequence[Any]:
"""Convert a single Agent Framework event to OpenAI events.
Args:
raw_event: Agent Framework event (AgentRunResponseUpdate, WorkflowEvent, etc.)
request: Original request for context
Returns:
List of OpenAI response stream events
"""
context = self._get_or_create_context(request)
# Handle error events
if isinstance(raw_event, dict) and raw_event.get("type") == "error":
return [await self._create_error_event(raw_event.get("message", "Unknown error"), context)]
# Handle ResponseTraceEvent objects from our trace collector
from .models import ResponseTraceEvent
if isinstance(raw_event, ResponseTraceEvent):
return [
ResponseTraceEventComplete(
type="response.trace.completed",
data=raw_event.data,
item_id=context["item_id"],
sequence_number=self._next_sequence(context),
)
]
# Handle Agent lifecycle events first
from .models._openai_custom import AgentCompletedEvent, AgentFailedEvent, AgentStartedEvent
if isinstance(raw_event, (AgentStartedEvent, AgentCompletedEvent, AgentFailedEvent)):
return await self._convert_agent_lifecycle_event(raw_event, context)
# Import Agent Framework types for proper isinstance checks
try:
from agent_framework import AgentRunResponse, AgentRunResponseUpdate, WorkflowEvent
from agent_framework._workflows._events import AgentRunUpdateEvent
# Handle AgentRunUpdateEvent - workflow event wrapping AgentRunResponseUpdate
# This must be checked BEFORE generic WorkflowEvent check
if isinstance(raw_event, AgentRunUpdateEvent):
# Extract the AgentRunResponseUpdate from the event's data attribute
if raw_event.data and isinstance(raw_event.data, AgentRunResponseUpdate):
# Preserve executor_id in context for proper output routing
context["current_executor_id"] = raw_event.executor_id
return await self._convert_agent_update(raw_event.data, context)
# If no data, treat as generic workflow event
return await self._convert_workflow_event(raw_event, context)
# Handle complete agent response (AgentRunResponse) - for non-streaming agent execution
if isinstance(raw_event, AgentRunResponse):
return await self._convert_agent_response(raw_event, context)
# Handle agent updates (AgentRunResponseUpdate) - for direct agent execution
if isinstance(raw_event, AgentRunResponseUpdate):
return await self._convert_agent_update(raw_event, context)
# Handle workflow events (any class that inherits from WorkflowEvent)
if isinstance(raw_event, WorkflowEvent):
return await self._convert_workflow_event(raw_event, context)
except ImportError as e:
logger.warning(f"Could not import Agent Framework types: {e}")
# Fallback to attribute-based detection
if hasattr(raw_event, "contents"):
return await self._convert_agent_update(raw_event, context)
if hasattr(raw_event, "__class__") and "Event" in raw_event.__class__.__name__:
return await self._convert_workflow_event(raw_event, context)
# Unknown event type
return [await self._create_unknown_event(raw_event, context)]
async def aggregate_to_response(self, events: Sequence[Any], request: AgentFrameworkRequest) -> OpenAIResponse:
"""Aggregate streaming events into final OpenAI response.
Args:
events: List of OpenAI stream events
request: Original request for context
Returns:
Final aggregated OpenAI response
"""
try:
# Extract text content from events
content_parts = []
for event in events:
# Extract delta text from ResponseTextDeltaEvent
if hasattr(event, "delta") and hasattr(event, "type") and event.type == "response.output_text.delta":
content_parts.append(event.delta)
# Combine content
full_content = "".join(content_parts)
# Create proper OpenAI Response
response_output_text = ResponseOutputText(type="output_text", text=full_content, annotations=[])
response_output_message = ResponseOutputMessage(
type="message",
role="assistant",
content=[response_output_text],
id=f"msg_{uuid.uuid4().hex[:8]}",
status="completed",
)
# Get usage from accumulator (OpenAI standard)
request_id = str(id(request))
usage_data = self._usage_accumulator.get(request_id)
if usage_data:
usage = ResponseUsage(
input_tokens=usage_data["input_tokens"],
output_tokens=usage_data["output_tokens"],
total_tokens=usage_data["total_tokens"],
input_tokens_details=InputTokensDetails(cached_tokens=0),
output_tokens_details=OutputTokensDetails(reasoning_tokens=0),
)
# Cleanup accumulator
del self._usage_accumulator[request_id]
else:
# Fallback: estimate if no usage was tracked
input_token_count = len(str(request.input)) // 4 if request.input else 0
output_token_count = len(full_content) // 4
usage = ResponseUsage(
input_tokens=input_token_count,
output_tokens=output_token_count,
total_tokens=input_token_count + output_token_count,
input_tokens_details=InputTokensDetails(cached_tokens=0),
output_tokens_details=OutputTokensDetails(reasoning_tokens=0),
)
return OpenAIResponse(
id=f"resp_{uuid.uuid4().hex[:12]}",
object="response",
created_at=datetime.now().timestamp(),
model=request.model or "devui",
output=[response_output_message],
usage=usage,
parallel_tool_calls=False,
tool_choice="none",
tools=[],
)
except Exception as e:
logger.exception(f"Error aggregating response: {e}")
return await self._create_error_response(str(e), request)
finally:
# Cleanup: Remove context after aggregation to prevent memory leak
# This handles the common case where streaming completes successfully
request_key = id(request)
if self._conversion_contexts.pop(request_key, None):
logger.debug(f"Cleaned up context for request {request_key} after aggregation")
def _get_or_create_context(self, request: AgentFrameworkRequest) -> dict[str, Any]:
"""Get or create conversion context for this request.
Uses LRU eviction when max_contexts is reached to prevent unbounded memory growth.
Args:
request: Request to get context for
Returns:
Conversion context dictionary
"""
request_key = id(request)
if request_key not in self._conversion_contexts:
# Evict oldest context if at capacity (LRU eviction)
if len(self._conversion_contexts) >= self._max_contexts:
evicted_key, _ = self._conversion_contexts.popitem(last=False)
logger.debug(f"Evicted oldest context (key={evicted_key}) - at max capacity ({self._max_contexts})")
self._conversion_contexts[request_key] = {
"sequence_counter": 0,
"item_id": f"msg_{uuid.uuid4().hex[:8]}",
"content_index": 0,
"output_index": 0,
"request_id": str(request_key), # For usage accumulation
"request": request, # Store the request for model name access
# Track active function calls: {call_id: {name, item_id, args_chunks}}
"active_function_calls": {},
}
else:
# Move to end (mark as recently used for LRU)
self._conversion_contexts.move_to_end(request_key)
return self._conversion_contexts[request_key]
def _next_sequence(self, context: dict[str, Any]) -> int:
"""Get next sequence number for events.
Args:
context: Conversion context
Returns:
Next sequence number
"""
context["sequence_counter"] += 1
return int(context["sequence_counter"])
def _serialize_value(self, value: Any) -> Any:
"""Recursively serialize a value, handling complex nested objects.
Handles:
- Primitives (str, int, float, bool, None)
- Collections (list, tuple, set, dict)
- SerializationMixin objects (ChatMessage, etc.) - calls to_dict()
- Pydantic models - calls model_dump()
- Dataclasses - recursively serializes with asdict()
- Enums - extracts value
- datetime/date/UUID - converts to ISO string
Args:
value: Value to serialize
Returns:
JSON-serializable representation
"""
from dataclasses import is_dataclass
from datetime import date, datetime
from enum import Enum
from uuid import UUID
# Handle None
if value is None:
return None
# Handle primitives
if isinstance(value, (str, int, float, bool)):
return value
# Handle datetime/date - convert to ISO format
if isinstance(value, datetime):
return value.isoformat()
if isinstance(value, date):
return value.isoformat()
# Handle UUID - convert to string
if isinstance(value, UUID):
return str(value)
# Handle Enums - extract value
if isinstance(value, Enum):
return value.value
# Handle lists/tuples/sets - recursively serialize elements
if isinstance(value, (list, tuple)):
return [self._serialize_value(item) for item in value]
if isinstance(value, set):
return [self._serialize_value(item) for item in value]
# Handle dicts - recursively serialize values
if isinstance(value, dict):
return {k: self._serialize_value(v) for k, v in value.items()}
# Handle SerializationMixin (like ChatMessage) - call to_dict()
if hasattr(value, "to_dict") and callable(getattr(value, "to_dict", None)):
try:
return value.to_dict() # type: ignore[attr-defined, no-any-return]
except Exception as e:
logger.debug(f"Failed to serialize with to_dict(): {e}")
return str(value)
# Handle Pydantic models - call model_dump()
if hasattr(value, "model_dump") and callable(getattr(value, "model_dump", None)):
try:
return value.model_dump() # type: ignore[attr-defined, no-any-return]
except Exception as e:
logger.debug(f"Failed to serialize Pydantic model: {e}")
return str(value)
# Handle dataclasses - recursively serialize with asdict
if is_dataclass(value) and not isinstance(value, type):
try:
from dataclasses import asdict
# Use our custom serializer as dict_factory
return asdict(value, dict_factory=lambda items: {k: self._serialize_value(v) for k, v in items})
except Exception as e:
logger.debug(f"Failed to serialize nested dataclass: {e}")
return str(value)
# Fallback: convert to string (for unknown types)
logger.debug(f"Serializing unknown type {type(value).__name__} as string")
return str(value)
def _serialize_request_data(self, request_data: Any) -> dict[str, Any]:
"""Serialize RequestInfoMessage to dict for JSON transmission.
Handles nested SerializationMixin objects (like ChatMessage) within dataclasses.
Args:
request_data: The RequestInfoMessage instance
Returns:
Serialized dict representation
"""
from dataclasses import asdict, fields, is_dataclass
if request_data is None:
return {}
# Handle dict first (most common)
if isinstance(request_data, dict):
return {k: self._serialize_value(v) for k, v in request_data.items()}
# Handle dataclasses with nested SerializationMixin objects
# We can't use asdict() directly because it doesn't handle ChatMessage
if is_dataclass(request_data) and not isinstance(request_data, type):
try:
# Manually serialize each field to handle nested SerializationMixin
result = {}
for field in fields(request_data):
field_value = getattr(request_data, field.name)
result[field.name] = self._serialize_value(field_value)
return result
except Exception as e:
logger.debug(f"Failed to serialize dataclass fields: {e}")
# Fallback to asdict() if our custom serialization fails
try:
return asdict(request_data) # type: ignore[arg-type]
except Exception as e2:
logger.debug(f"Failed to serialize dataclass with asdict(): {e2}")
# Handle Pydantic models (have model_dump method)
if hasattr(request_data, "model_dump") and callable(getattr(request_data, "model_dump", None)):
try:
return request_data.model_dump() # type: ignore[attr-defined, no-any-return]
except Exception as e:
logger.debug(f"Failed to serialize Pydantic model: {e}")
# Handle SerializationMixin (have to_dict method)
if hasattr(request_data, "to_dict") and callable(getattr(request_data, "to_dict", None)):
try:
return request_data.to_dict() # type: ignore[attr-defined, no-any-return]
except Exception as e:
logger.debug(f"Failed to serialize with to_dict(): {e}")
# Fallback: string representation
return {"raw": str(request_data)}
async def _convert_agent_update(self, update: Any, context: dict[str, Any]) -> Sequence[Any]:
"""Convert agent text updates to proper content part events.
Args:
update: Agent run response update
context: Conversion context
Returns:
List of OpenAI response stream events
"""
events: list[Any] = []
try:
# Handle different update types
if not hasattr(update, "contents") or not update.contents:
return events
# Check if we're streaming text content
has_text_content = any(content.__class__.__name__ == "TextContent" for content in update.contents)
# Check if we're in an executor context with an existing item
executor_id = context.get("current_executor_id")
executor_item_key = f"exec_item_{executor_id}" if executor_id else None
# If we have an executor item, use it for deltas instead of creating a message
if has_text_content and executor_item_key and executor_item_key in context:
# Use the executor's item ID for this agent's output
context["current_message_id"] = context[executor_item_key]
# Note: We don't create a new message item here since the executor item already exists
# Otherwise, create a message item if we haven't yet (for non-executor contexts)
elif has_text_content and "current_message_id" not in context:
message_id = f"msg_{uuid4().hex[:8]}"
context["current_message_id"] = message_id
context["output_index"] = context.get("output_index", -1) + 1
# Add message output item
events.append(
ResponseOutputItemAddedEvent(
type="response.output_item.added",
output_index=context["output_index"],
sequence_number=self._next_sequence(context),
item=ResponseOutputMessage(
type="message", id=message_id, role="assistant", content=[], status="in_progress"
),
)
)
# Add content part for text
context["content_index"] = 0
events.append(
ResponseContentPartAddedEvent(
type="response.content_part.added",
output_index=context["output_index"],
content_index=context["content_index"],
item_id=message_id,
sequence_number=self._next_sequence(context),
part=ResponseOutputText(type="output_text", text="", annotations=[]),
)
)
# Process each content item
for content in update.contents:
content_type = content.__class__.__name__
# Special handling for TextContent to use proper delta events
if content_type == "TextContent" and "current_message_id" in context:
# Stream text content via proper delta events
events.append(
ResponseTextDeltaEvent(
type="response.output_text.delta",
output_index=context["output_index"],
content_index=context.get("content_index", 0),
item_id=context["current_message_id"],
delta=content.text,
logprobs=[], # We don't have logprobs from Agent Framework
sequence_number=self._next_sequence(context),
)
)
elif content_type in self.content_mappers:
# Use existing mappers for other content types
mapped_events = await self.content_mappers[content_type](content, context)
if mapped_events is not None: # Handle None returns (e.g., UsageContent)
if isinstance(mapped_events, list):
events.extend(mapped_events)
else:
events.append(mapped_events)
else:
# Graceful fallback for unknown content types
events.append(await self._create_unknown_content_event(content, context))
# Don't increment content_index for text deltas within the same part
if content_type != "TextContent":
context["content_index"] = context.get("content_index", 0) + 1
except Exception as e:
logger.warning(f"Error converting agent update: {e}")
events.append(await self._create_error_event(str(e), context))
return events
async def _convert_agent_response(self, response: Any, context: dict[str, Any]) -> Sequence[Any]:
"""Convert complete AgentRunResponse to OpenAI events.
This handles non-streaming agent execution where agent.run() returns
a complete AgentRunResponse instead of streaming AgentRunResponseUpdate objects.
Args:
response: Agent run response (AgentRunResponse)
context: Conversion context
Returns:
List of OpenAI response stream events
"""
events: list[Any] = []
try:
# Extract all messages from the response
messages = getattr(response, "messages", [])
# Convert each message's contents to streaming events
for message in messages:
if hasattr(message, "contents") and message.contents:
for content in message.contents:
content_type = content.__class__.__name__
if content_type in self.content_mappers:
mapped_events = await self.content_mappers[content_type](content, context)
if mapped_events is not None: # Handle None returns (e.g., UsageContent)
if isinstance(mapped_events, list):
events.extend(mapped_events)
else:
events.append(mapped_events)
else:
# Graceful fallback for unknown content types
events.append(await self._create_unknown_content_event(content, context))
context["content_index"] += 1
# Add usage information if present
usage_details = getattr(response, "usage_details", None)
if usage_details:
from agent_framework import UsageContent
usage_content = UsageContent(details=usage_details)
await self._map_usage_content(usage_content, context)
# Note: _map_usage_content returns None - it accumulates usage for final Response.usage
except Exception as e:
logger.warning(f"Error converting agent response: {e}")
events.append(await self._create_error_event(str(e), context))
return events
async def _convert_agent_lifecycle_event(self, event: Any, context: dict[str, Any]) -> Sequence[Any]:
"""Convert agent lifecycle events to OpenAI response events.
Args:
event: AgentStartedEvent, AgentCompletedEvent, or AgentFailedEvent
context: Conversion context
Returns:
List of OpenAI response stream events
"""
from .models._openai_custom import AgentCompletedEvent, AgentFailedEvent, AgentStartedEvent
try:
# Get model name from request or use 'devui' as default
request_obj = context.get("request")
model_name = request_obj.model if request_obj and request_obj.model else "devui"
if isinstance(event, AgentStartedEvent):
execution_id = f"agent_{uuid4().hex[:12]}"
context["execution_id"] = execution_id
# Create Response object
response_obj = Response(
id=f"resp_{execution_id}",
object="response",
created_at=float(time.time()),
model=model_name,
output=[],
status="in_progress",
parallel_tool_calls=False,
tool_choice="none",
tools=[],
)
# Emit both created and in_progress events
return [
ResponseCreatedEvent(
type="response.created", sequence_number=self._next_sequence(context), response=response_obj
),
ResponseInProgressEvent(
type="response.in_progress", sequence_number=self._next_sequence(context), response=response_obj
),
]
if isinstance(event, AgentCompletedEvent):
# Don't emit response.completed here - the server will emit a proper one
# with usage data after aggregating all events
return []
if isinstance(event, AgentFailedEvent):
execution_id = context.get("execution_id", f"agent_{uuid4().hex[:12]}")
# Create error object
response_error = ResponseError(
message=str(event.error) if event.error else "Unknown error", code="server_error"
)
response_obj = Response(
id=f"resp_{execution_id}",
object="response",
created_at=float(time.time()),
model=model_name,
output=[],
status="failed",
error=response_error,
parallel_tool_calls=False,
tool_choice="none",
tools=[],
)
return [
ResponseFailedEvent(
type="response.failed", sequence_number=self._next_sequence(context), response=response_obj
)
]
return []
except Exception as e:
logger.warning(f"Error converting agent lifecycle event: {e}")
return [await self._create_error_event(str(e), context)]
async def _convert_workflow_event(self, event: Any, context: dict[str, Any]) -> Sequence[Any]:
"""Convert workflow events to standard OpenAI event objects.
Args:
event: Workflow event
context: Conversion context
Returns:
List of OpenAI response stream events
"""
try:
event_class = event.__class__.__name__
# Response-level events - construct proper OpenAI objects
if event_class == "WorkflowStartedEvent":
workflow_id = getattr(event, "workflow_id", str(uuid4()))
context["workflow_id"] = workflow_id
# Import Response type for proper construction
from openai.types.responses import Response
# Return proper OpenAI event objects
events: list[Any] = []
# Get model name from request or use 'devui' as default
request_obj = context.get("request")
model_name = request_obj.model if request_obj and request_obj.model else "devui"
# Create a full Response object with all required fields
response_obj = Response(
id=f"resp_{workflow_id}",
object="response",
created_at=float(time.time()),
model=model_name,
output=[], # Empty output list initially
status="in_progress",
# Required fields with safe defaults
parallel_tool_calls=False,
tool_choice="none",
tools=[],
)
# First emit response.created
events.append(
ResponseCreatedEvent(
type="response.created", sequence_number=self._next_sequence(context), response=response_obj
)
)
# Then emit response.in_progress (reuse same response object)
events.append(
ResponseInProgressEvent(
type="response.in_progress", sequence_number=self._next_sequence(context), response=response_obj
)
)
return events
# Handle WorkflowOutputEvent separately to preserve output data
if event_class == "WorkflowOutputEvent":
output_data = getattr(event, "data", None)
source_executor_id = getattr(event, "source_executor_id", "unknown")
if output_data is not None:
# Import required types
from openai.types.responses import ResponseOutputMessage, ResponseOutputText
from openai.types.responses.response_output_item_added_event import ResponseOutputItemAddedEvent
# Increment output index for each yield_output
context["output_index"] = context.get("output_index", -1) + 1
# Extract text from output data based on type
text = None
if hasattr(output_data, "__class__") and output_data.__class__.__name__ == "ChatMessage":
# Handle ChatMessage (from Magentic and AgentExecutor with output_response=True)
text = getattr(output_data, "text", None)
if not text:
# Fallback to string representation
text = str(output_data)
elif isinstance(output_data, str):
# String output
text = output_data
else:
# Object/dict/list → JSON string
try:
text = json.dumps(output_data, indent=2)
except (TypeError, ValueError):
# Fallback to string representation if not JSON serializable
text = str(output_data)
# Create output message with text content
text_content = ResponseOutputText(type="output_text", text=text, annotations=[])
output_message = ResponseOutputMessage(
type="message",
id=f"msg_{uuid4().hex[:8]}",
role="assistant",
content=[text_content],
status="completed",
)
# Emit output_item.added for each yield_output
logger.debug(
f"WorkflowOutputEvent converted to output_item.added "
f"(executor: {source_executor_id}, length: {len(text)})"
)
return [
ResponseOutputItemAddedEvent(
type="response.output_item.added",
item=output_message,
output_index=context["output_index"],
sequence_number=self._next_sequence(context),
)
]
# Handle WorkflowCompletedEvent - Don't emit response.completed here
# The server will emit a proper one with usage data after aggregating all events
if event_class == "WorkflowCompletedEvent":
return []
if event_class == "WorkflowFailedEvent":
workflow_id = context.get("workflow_id", str(uuid4()))
error_info = getattr(event, "error", None)
# Import Response and ResponseError types
from openai.types.responses import Response, ResponseError
# Get model name from request or use 'devui' as default
request_obj = context.get("request")
model_name = request_obj.model if request_obj and request_obj.model else "devui"
# Create error object
error_message = str(error_info) if error_info else "Unknown error"
# Create ResponseError object (code must be one of the allowed values)
response_error = ResponseError(
message=error_message,
code="server_error", # Use generic server_error code for workflow failures
)
# Create a full Response object for failed state
response_obj = Response(
id=f"resp_{workflow_id}",
object="response",
created_at=float(time.time()),
model=model_name,
output=[],
status="failed",
error=response_error,
parallel_tool_calls=False,
tool_choice="none",
tools=[],
)
return [
ResponseFailedEvent(
type="response.failed", sequence_number=self._next_sequence(context), response=response_obj
)
]
# Executor-level events (output items)
if event_class == "ExecutorInvokedEvent":
executor_id = getattr(event, "executor_id", "unknown")
item_id = f"exec_{executor_id}_{uuid4().hex[:8]}"
context[f"exec_item_{executor_id}"] = item_id
context["output_index"] = context.get("output_index", -1) + 1
# Track current executor for routing Magentic agent events
# This allows MagenticAgentDeltaEvent to route to the executor's item
context["current_executor_id"] = executor_id
# Create ExecutorActionItem with proper type
executor_item = ExecutorActionItem(
type="executor_action",
id=item_id,
executor_id=executor_id,
status="in_progress",
metadata=getattr(event, "metadata", {}),
)
# Use our custom event type that accepts ExecutorActionItem
return [
CustomResponseOutputItemAddedEvent(
type="response.output_item.added",
output_index=context["output_index"],
sequence_number=self._next_sequence(context),
item=executor_item,
)
]
if event_class == "ExecutorCompletedEvent":
executor_id = getattr(event, "executor_id", "unknown")
item_id = context.get(f"exec_item_{executor_id}", f"exec_{executor_id}_unknown")
# Clear current executor tracking when executor completes
if context.get("current_executor_id") == executor_id:
context.pop("current_executor_id", None)
# Create ExecutorActionItem with completed status
# ExecutorCompletedEvent uses 'data' field, not 'result'
# Serialize the result data to ensure it's JSON-serializable
# (AgentExecutorResponse contains AgentRunResponse/ChatMessage which are SerializationMixin)
raw_result = getattr(event, "data", None)
serialized_result = self._serialize_value(raw_result) if raw_result is not None else None
executor_item = ExecutorActionItem(
type="executor_action",
id=item_id,
executor_id=executor_id,
status="completed",
result=serialized_result,
)
# Use our custom event type
return [
CustomResponseOutputItemDoneEvent(
type="response.output_item.done",
output_index=context.get("output_index", 0),
sequence_number=self._next_sequence(context),
item=executor_item,
)
]
if event_class == "ExecutorFailedEvent":
executor_id = getattr(event, "executor_id", "unknown")
item_id = context.get(f"exec_item_{executor_id}", f"exec_{executor_id}_unknown")
# ExecutorFailedEvent uses 'details' field (WorkflowErrorDetails), not 'error'
details = getattr(event, "details", None)
err_msg: str | None = str(getattr(details, "message", details)) if details else None
# Create ExecutorActionItem with failed status
executor_item = ExecutorActionItem(
type="executor_action",
id=item_id,
executor_id=executor_id,
status="failed",
error={"message": err_msg} if err_msg else None,
)
# Use our custom event type
return [
CustomResponseOutputItemDoneEvent(
type="response.output_item.done",
output_index=context.get("output_index", 0),
sequence_number=self._next_sequence(context),
item=executor_item,
)
]
# Handle RequestInfoEvent specially - emit as HIL event with schema
if event_class == "RequestInfoEvent":
from .models._openai_custom import ResponseRequestInfoEvent
request_id = getattr(event, "request_id", "")
source_executor_id = getattr(event, "source_executor_id", "")
request_type_class = getattr(event, "request_type", None)
request_data = getattr(event, "data", None)
logger.info("📨 [MAPPER] Processing RequestInfoEvent")
logger.info(f" request_id: {request_id}")
logger.info(f" source_executor_id: {source_executor_id}")
logger.info(f" request_type_class: {request_type_class}")
logger.info(f" request_data: {request_data}")
# Serialize request data
serialized_data = self._serialize_request_data(request_data)
logger.info(f" serialized_data: {serialized_data}")
# Get request type name for debugging
request_type_name = "Unknown"
if request_type_class:
request_type_name = f"{request_type_class.__module__}:{request_type_class.__name__}"
# Get response schema that was attached by executor
# This tells the UI what format to collect from the user
response_schema = getattr(event, "_response_schema", None)
if not response_schema:
# Fallback to string if somehow not set (shouldn't happen with current executor enrichment)
logger.warning(f"⚠️ Response schema not found for {request_type_name}, using default")
response_schema = {"type": "string"}
else: