-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy path__init__.py
More file actions
916 lines (844 loc) · 45.4 KB
/
__init__.py
File metadata and controls
916 lines (844 loc) · 45.4 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
"""
Basic orchestrator with complete event emissions (desired state).
"""
# Amplifier module metadata
__amplifier_module_type__ = "orchestrator"
import asyncio
import json
import logging
from typing import Any
from amplifier_core import HookRegistry
from amplifier_core import HookResult
from amplifier_core import ModuleCoordinator
from amplifier_core.events import CONTENT_BLOCK_END
from amplifier_core.events import CONTENT_BLOCK_START
from amplifier_core.events import EXECUTION_END
from amplifier_core.events import EXECUTION_START
from amplifier_core.events import ORCHESTRATOR_COMPLETE
from amplifier_core.events import PROMPT_COMPLETE
from amplifier_core.events import PROMPT_SUBMIT
from amplifier_core.events import PROVIDER_ERROR
from amplifier_core.events import PROVIDER_REQUEST
from amplifier_core.events import PROVIDER_RESPONSE
from amplifier_core.events import TOOL_ERROR
from amplifier_core.events import TOOL_POST
from amplifier_core.events import TOOL_PRE
from amplifier_core.llm_errors import LLMError
from amplifier_core.message_models import ChatRequest
from amplifier_core.message_models import Message
from amplifier_core.message_models import ToolSpec
logger = logging.getLogger(__name__)
async def mount(coordinator: ModuleCoordinator, config: dict[str, Any] | None = None):
config = config or {}
coordinator.register_contributor(
"observability.events",
"loop-basic",
lambda: [
"execution:start",
"execution:end",
],
)
orchestrator = BasicOrchestrator(config)
await coordinator.mount("orchestrator", orchestrator)
logger.info("Mounted BasicOrchestrator (desired-state)")
return
class BasicOrchestrator:
def __init__(self, config: dict[str, Any]) -> None:
self.config = config
# -1 means unlimited iterations (default)
max_iter_config = config.get("max_iterations", -1)
self.max_iterations = int(max_iter_config) if max_iter_config != -1 else -1
self.default_provider: str | None = config.get("default_provider")
self.extended_thinking = config.get("extended_thinking", False)
# Store ephemeral injections from tool:post hooks for next iteration
self._pending_ephemeral_injections: list[dict[str, Any]] = []
async def execute(
self,
prompt: str,
context,
providers: dict[str, Any],
tools: dict[str, Any],
hooks: HookRegistry,
coordinator: ModuleCoordinator | None = None,
) -> str:
# Emit and process prompt submit (allows hooks to inject context on session start)
result = await hooks.emit(PROMPT_SUBMIT, {"prompt": prompt})
if coordinator:
result = await coordinator.process_hook_result(
result, "prompt:submit", "orchestrator"
)
if result.action == "deny":
return f"Operation denied: {result.reason}"
# Emit execution start (after prompt:submit so denials skip this)
await hooks.emit(EXECUTION_START, {"prompt": prompt})
# Add user message
if hasattr(context, "add_message"):
await context.add_message({"role": "user", "content": prompt})
# Select provider based on priority
provider = self._select_provider(providers)
if not provider:
raise RuntimeError("No provider available")
provider_name = None
for name, prov in providers.items():
if prov is provider:
provider_name = name
break
# Agentic loop: continue until we get a text response (no tool calls)
iteration = 0
final_content = ""
execution_status = "completed"
try:
while self.max_iterations == -1 or iteration < self.max_iterations:
# Check for cancellation at iteration start
if coordinator and coordinator.cancellation.is_cancelled:
# Emit orchestrator complete with cancelled status
await hooks.emit(
ORCHESTRATOR_COMPLETE,
{
"orchestrator": "loop-basic",
"turn_count": iteration,
"status": "cancelled",
},
)
execution_status = "cancelled"
return final_content
# Emit provider request BEFORE getting messages (allows hook injections)
result = await hooks.emit(
PROVIDER_REQUEST,
{"provider": provider_name, "iteration": iteration},
)
if coordinator:
result = await coordinator.process_hook_result(
result, "provider:request", "orchestrator"
)
if result.action == "deny":
return f"Operation denied: {result.reason}"
# Get messages for LLM request (context handles compaction internally)
# Pass provider for dynamic budget calculation based on model's context window
if hasattr(context, "get_messages_for_request"):
message_dicts = await context.get_messages_for_request(
provider=provider
)
else:
# Fallback for simple contexts without the method
message_dicts = getattr(
context, "messages", [{"role": "user", "content": prompt}]
)
# Append ephemeral injection if present (temporary, not stored)
if (
result.action == "inject_context"
and result.ephemeral
and result.context_injection
):
message_dicts = list(
message_dicts
) # Copy to avoid modifying context
# Check if we should append to last tool result
if result.append_to_last_tool_result and len(message_dicts) > 0:
last_msg = message_dicts[-1]
# Append to last message if it's a tool result
if last_msg.get("role") == "tool":
# Append to existing content
original_content = last_msg.get("content", "")
message_dicts[-1] = {
**last_msg,
"content": f"{original_content}\n\n{result.context_injection}",
}
logger.debug(
"Appended ephemeral injection to last tool result message"
)
else:
# Fall back to new message if last message isn't a tool result
message_dicts.append(
{
"role": result.context_injection_role,
"content": result.context_injection,
}
)
logger.debug(
f"Last message role is '{last_msg.get('role')}', not 'tool' - "
"created new message for injection"
)
else:
# Default behavior: append as new message
message_dicts.append(
{
"role": result.context_injection_role,
"content": result.context_injection,
}
)
# Apply pending ephemeral injections from tool:post hooks
if self._pending_ephemeral_injections:
message_dicts = list(message_dicts) # Ensure we have a mutable list
for injection in self._pending_ephemeral_injections:
if (
injection.get("append_to_last_tool_result")
and len(message_dicts) > 0
):
last_msg = message_dicts[-1]
if last_msg.get("role") == "tool":
original_content = last_msg.get("content", "")
message_dicts[-1] = {
**last_msg,
"content": f"{original_content}\n\n{injection['content']}",
}
logger.debug(
"Applied pending ephemeral injection to last tool result"
)
else:
message_dicts.append(
{
"role": injection["role"],
"content": injection["content"],
}
)
logger.debug(
"Last message not a tool result, created new message for injection"
)
else:
message_dicts.append(
{
"role": injection["role"],
"content": injection["content"],
}
)
logger.debug(
"Applied pending ephemeral injection as new message"
)
# Clear pending injections after applying
self._pending_ephemeral_injections = []
# Convert to ChatRequest with Message objects
try:
messages_objects = [Message(**msg) for msg in message_dicts]
# Convert tools to ToolSpec format for ChatRequest
tools_list = None
if tools:
tools_list = [
ToolSpec(
name=t.name,
description=t.description,
parameters=t.input_schema,
)
for t in tools.values()
]
chat_request = ChatRequest(
messages=messages_objects,
tools=tools_list,
reasoning_effort=self.config.get("reasoning_effort"),
)
logger.debug(
f"Created ChatRequest with {len(messages_objects)} messages"
)
logger.debug(
f"Message roles: {[m.role for m in chat_request.messages]}"
)
except Exception as e:
logger.error(f"Failed to create ChatRequest: {e}")
logger.error(f"Message dicts: {message_dicts}")
raise
try:
if hasattr(provider, "complete"):
# Pass extended_thinking if enabled in orchestrator config
kwargs = {}
if self.extended_thinking:
kwargs["extended_thinking"] = True
response = await provider.complete(chat_request, **kwargs)
# Check for immediate cancellation after provider returns
# This allows force-cancel to take effect as soon as the blocking
# provider call completes, before processing the response
if coordinator and coordinator.cancellation.is_immediate:
# Emit cancelled status and exit
await hooks.emit(
ORCHESTRATOR_COMPLETE,
{
"orchestrator": "loop-basic",
"turn_count": iteration,
"status": "cancelled",
},
)
execution_status = "cancelled"
return final_content
else:
raise RuntimeError(
f"Provider {provider_name} missing 'complete'"
)
usage = getattr(response, "usage", None)
content = getattr(response, "content", None)
tool_calls = getattr(response, "tool_calls", None)
await hooks.emit(
PROVIDER_RESPONSE,
{
"provider": provider_name,
"usage": usage,
"tool_calls": bool(tool_calls),
},
)
# Emit content block events if present
content_blocks = getattr(response, "content_blocks", None)
logger.info(
f"Response has content_blocks: {content_blocks is not None} - count: {len(content_blocks) if content_blocks else 0}"
)
if content_blocks:
total_blocks = len(content_blocks)
logger.info(
f"Emitting events for {total_blocks} content blocks"
)
for idx, block in enumerate(content_blocks):
logger.info(
f"Emitting CONTENT_BLOCK_START for block {idx}, type: {block.type.value}"
)
# Emit block start (without non-serializable raw object)
await hooks.emit(
CONTENT_BLOCK_START,
{
"block_type": block.type.value,
"block_index": idx,
"total_blocks": total_blocks,
},
)
# Emit block end with complete block, usage, and total count
event_data = {
"block_index": idx,
"total_blocks": total_blocks,
"block": block.to_dict(),
}
if usage:
event_data["usage"] = (
usage.model_dump()
if hasattr(usage, "model_dump")
else usage
)
await hooks.emit(CONTENT_BLOCK_END, event_data)
# Handle tool calls (parallel execution)
if tool_calls:
# Add assistant message with tool calls BEFORE executing them
if hasattr(context, "add_message"):
# Store structured content from response.content (our Pydantic models)
response_content = getattr(response, "content", None)
if response_content and isinstance(response_content, list):
assistant_msg = {
"role": "assistant",
"content": [
block.model_dump()
if hasattr(block, "model_dump")
else block
for block in response_content
],
"tool_calls": [
{
"id": tc.id if hasattr(tc, "id") else tc.get("id"),
"tool": tc.name if hasattr(tc, "name") else tc.get("tool"),
"arguments": tc.arguments if hasattr(tc, "arguments") else (tc.get("arguments") or {}),
}
for tc in tool_calls
],
}
else:
assistant_msg = {
"role": "assistant",
"content": content if content else "",
"tool_calls": [
{
"id": tc.id if hasattr(tc, "id") else tc.get("id"),
"tool": tc.name if hasattr(tc, "name") else tc.get("tool"),
"arguments": tc.arguments if hasattr(tc, "arguments") else (tc.get("arguments") or {}),
}
for tc in tool_calls
],
}
# Preserve provider metadata (provider-agnostic passthrough)
# This enables providers to maintain state across steps (e.g., OpenAI reasoning items)
if hasattr(response, "metadata") and response.metadata:
assistant_msg["metadata"] = response.metadata
await context.add_message(assistant_msg)
# Execute tools in parallel (user guidance: assume parallel intent when multiple tool calls)
import uuid
# Generate parallel group ID for event correlation
parallel_group_id = str(uuid.uuid4())
# Create tasks for parallel execution
async def execute_single_tool(
tc: Any, group_id: str
) -> tuple[str, str]:
"""Execute one tool, handling all errors gracefully.
Always returns (tool_call_id, result_or_error) tuple.
Never raises - errors become error results.
"""
tool_name = tc.name if hasattr(tc, "name") else tc.get("tool")
tool_call_id = tc.id if hasattr(tc, "id") else tc.get("id")
args = (
tc.arguments if hasattr(tc, "arguments") else (tc.get("arguments") or {})
)
tool = tools.get(tool_name)
# Register tool with cancellation token for visibility
if coordinator:
coordinator.cancellation.register_tool_start(
tool_call_id, tool_name
)
# Set dispatch context so tools (e.g. delegate) can
# read the framework-assigned tool_call_id and
# parallel_group_id. Cleared in the finally block.
setattr(
coordinator,
"_tool_dispatch_context",
{
"tool_call_id": tool_call_id,
"parallel_group_id": group_id,
},
)
try:
try:
# Emit and process tool pre (allows hooks to block or request approval)
pre_result = await hooks.emit(
TOOL_PRE,
{
"tool_name": tool_name,
"tool_call_id": tool_call_id,
"tool_input": args,
"parallel_group_id": group_id,
},
)
if coordinator:
pre_result = (
await coordinator.process_hook_result(
pre_result, "tool:pre", tool_name
)
)
if pre_result.action == "deny":
return (
tool_call_id,
f"Denied by hook: {pre_result.reason}",
)
if not tool:
error_msg = (
f"Error: Tool '{tool_name}' not found"
)
await hooks.emit(
TOOL_ERROR,
{
"tool_name": tool_name,
"tool_call_id": tool_call_id,
"error": {
"type": "RuntimeError",
"msg": error_msg,
},
"parallel_group_id": group_id,
},
)
return (tool_call_id, error_msg)
result = await tool.execute(args)
# Serialize result for logging
result_data = result
if hasattr(result, "to_dict"):
result_data = result.to_dict()
# Emit and process tool post (allows hooks to inject feedback)
post_result = await hooks.emit(
TOOL_POST,
{
"tool_name": tool_name,
"tool_call_id": tool_call_id,
"tool_input": args,
"result": result_data,
"parallel_group_id": group_id,
},
)
if coordinator:
await coordinator.process_hook_result(
post_result, "tool:post", tool_name
)
# Store ephemeral injection from tool:post for next iteration
if (
post_result.action == "inject_context"
and post_result.ephemeral
and post_result.context_injection
):
self._pending_ephemeral_injections.append(
{
"role": post_result.context_injection_role,
"content": post_result.context_injection,
"append_to_last_tool_result": post_result.append_to_last_tool_result,
}
)
logger.debug(
f"Stored ephemeral injection from tool:post ({tool_name}) for next iteration"
)
# Check if a hook modified the tool result.
# hooks.emit() chains modify actions: when a hook
# returns action="modify", the data dict is replaced.
# We detect this by checking if the returned "result"
# is a different object than what we originally sent.
modified_result = None
if post_result and post_result.data is not None:
returned_result = post_result.data.get("result")
if (
returned_result is not None
and returned_result is not result_data
):
modified_result = returned_result
if modified_result is not None:
if isinstance(modified_result, (dict, list)):
result_content = json.dumps(modified_result)
else:
result_content = str(modified_result)
else:
result_content = result.get_serialized_output()
return (tool_call_id, result_content)
except (Exception, asyncio.CancelledError) as te:
# Emit error event
await hooks.emit(
TOOL_ERROR,
{
"tool_name": tool_name,
"tool_call_id": tool_call_id,
"error": {
"type": type(te).__name__,
"msg": str(te),
},
"parallel_group_id": group_id,
},
)
# Return failure with error message (don't raise!)
error_msg = f"Error executing tool: {str(te)}"
logger.error(f"Tool {tool_name} failed: {te}")
return (tool_call_id, error_msg)
finally:
# Clear dispatch context and unregister tool
if coordinator:
setattr(coordinator, "_tool_dispatch_context", {})
coordinator.cancellation.register_tool_complete(
tool_call_id
)
# Execute all tools in parallel with asyncio.gather
# return_exceptions=False because we handle exceptions inside execute_single_tool
# Wrap in try/except for CancelledError to handle immediate cancellation
try:
tool_results = await asyncio.gather(
*[
execute_single_tool(tc, parallel_group_id)
for tc in tool_calls
]
)
except asyncio.CancelledError:
# Immediate cancellation (second Ctrl+C) - synthesize cancelled results
# for ALL tool_calls to maintain tool_use/tool_result pairing.
# Protect from further CancelledError using kernel
# catch-continue-reraise pattern so all results are written.
logger.info(
"Tool execution cancelled - synthesizing cancelled results"
)
for tc in tool_calls:
try:
if hasattr(context, "add_message"):
await context.add_message(
{
"role": "tool",
"tool_call_id": tc.id if hasattr(tc, "id") else tc.get("id"),
"content": f'{{"error": "Tool execution was cancelled by user", "cancelled": true, "tool": "{tc.name if hasattr(tc, "name") else tc.get("tool")}"}}',
}
)
except asyncio.CancelledError:
logger.info(
"CancelledError during synthetic result write - "
"completing remaining writes to prevent "
"orphaned tool_calls"
)
# Re-raise to let the cancellation propagate
raise
# Check for immediate cancellation (graceful path - tools completed)
if coordinator and coordinator.cancellation.is_immediate:
# MUST add tool results to context before returning
# Otherwise we leave orphaned tool_calls without matching tool_results
# which violates provider API contracts (Anthropic, OpenAI)
# Protect from CancelledError using kernel catch-continue-reraise
# pattern (coordinator.cleanup, hooks.emit) so all results are
# written even if force-cancel arrives mid-loop.
_cancel_error = None
for tool_call_id, content in tool_results:
try:
if hasattr(context, "add_message"):
await context.add_message(
{
"role": "tool",
"tool_call_id": tool_call_id,
"content": content,
}
)
except asyncio.CancelledError:
if _cancel_error is None:
_cancel_error = asyncio.CancelledError()
logger.info(
"CancelledError during tool result write - "
"completing remaining writes to prevent "
"orphaned tool_calls"
)
if _cancel_error is not None:
raise _cancel_error
await hooks.emit(
ORCHESTRATOR_COMPLETE,
{
"orchestrator": "loop-basic",
"turn_count": iteration,
"status": "cancelled",
},
)
execution_status = "cancelled"
return final_content
# Add all tool results to context in original order (deterministic)
# Protect from CancelledError using kernel catch-continue-reraise
# pattern so all results are written even if force-cancel arrives
# mid-loop.
_cancel_error = None
for tool_call_id, content in tool_results:
try:
if hasattr(context, "add_message"):
await context.add_message(
{
"role": "tool",
"tool_call_id": tool_call_id,
"content": content,
}
)
except asyncio.CancelledError:
if _cancel_error is None:
_cancel_error = asyncio.CancelledError()
logger.info(
"CancelledError during tool result write - "
"completing remaining writes to prevent "
"orphaned tool_calls"
)
if _cancel_error is not None:
raise _cancel_error
# After executing tools, continue loop to get final response
iteration += 1
continue
# If we have content (no tool calls), we're done
if content:
# Extract text from content blocks
if isinstance(content, list):
text_parts = []
for block in content:
if hasattr(block, "text"):
text_parts.append(block.text)
elif isinstance(block, dict) and "text" in block:
text_parts.append(block["text"])
final_content = (
"\n\n".join(text_parts) if text_parts else ""
)
else:
final_content = content
if hasattr(context, "add_message"):
# Store structured content from response.content (our Pydantic models)
response_content = getattr(response, "content", None)
if response_content and isinstance(response_content, list):
assistant_msg = {
"role": "assistant",
"content": [
block.model_dump()
if hasattr(block, "model_dump")
else block
for block in response_content
],
}
else:
assistant_msg = {
"role": "assistant",
"content": content,
}
# Preserve provider metadata (provider-agnostic passthrough)
if hasattr(response, "metadata") and response.metadata:
assistant_msg["metadata"] = response.metadata
await context.add_message(assistant_msg)
break
# No content and no tool calls - this shouldn't happen but handle it
logger.warning("Provider returned neither content nor tool calls")
iteration += 1
except LLMError as e:
await hooks.emit(
PROVIDER_ERROR,
{
"provider": provider_name,
"error": {"type": type(e).__name__, "msg": str(e)},
"retryable": e.retryable,
"status_code": e.status_code,
},
)
raise
except Exception as e:
await hooks.emit(
PROVIDER_ERROR,
{
"provider": provider_name,
"error": {"type": type(e).__name__, "msg": str(e)},
},
)
raise
# Check if we exceeded max iterations (only if not unlimited)
if (
self.max_iterations != -1
and iteration >= self.max_iterations
and not final_content
):
logger.warning(
f"Max iterations ({self.max_iterations}) reached without final response"
)
# Inject system reminder to agent before final response
await hooks.emit(
PROVIDER_REQUEST,
{
"provider": provider_name,
"iteration": iteration,
"max_reached": True,
},
)
if coordinator:
# Inject ephemeral reminder (not stored in context)
await coordinator.process_hook_result(
HookResult(
action="inject_context",
context_injection="""<system-reminder>
You have reached the maximum number of iterations for this turn. Please provide a response to the user now, summarizing your progress and noting what remains to be done. You can continue in the next turn if needed.
</system-reminder>""",
context_injection_role="system",
ephemeral=True,
suppress_output=True,
),
"provider:request",
"orchestrator",
)
# Get one final response with the reminder (context handles compaction internally)
if hasattr(context, "get_messages_for_request"):
message_dicts = await context.get_messages_for_request(
provider=provider
)
else:
message_dicts = getattr(
context, "messages", [{"role": "user", "content": prompt}]
)
message_dicts = list(message_dicts)
message_dicts.append(
{
"role": "user",
"content": """<system-reminder source="orchestrator-loop-limit">
You have reached the maximum number of iterations for this turn. Please provide a response to the user now, summarizing your progress and noting what remains to be done. You can continue in the next turn if needed.
DO NOT mention this iteration limit or reminder to the user explicitly. Simply wrap up naturally.
</system-reminder>""",
}
)
try:
messages_objects = [Message(**msg) for msg in message_dicts]
# Convert tools to ToolSpec format for ChatRequest
tools_list = None
if tools:
tools_list = [
ToolSpec(
name=t.name,
description=t.description,
parameters=t.input_schema,
)
for t in tools.values()
]
chat_request = ChatRequest(
messages=messages_objects,
tools=tools_list,
reasoning_effort=self.config.get("reasoning_effort"),
)
kwargs = {}
if self.extended_thinking:
kwargs["extended_thinking"] = True
response = await provider.complete(chat_request, **kwargs)
content = getattr(response, "content", None)
content_blocks = getattr(response, "content_blocks", None)
if content:
final_content = content
if hasattr(context, "add_message"):
# Store structured content from response.content (our Pydantic models)
response_content = getattr(response, "content", None)
if response_content and isinstance(response_content, list):
assistant_msg = {
"role": "assistant",
"content": [
block.model_dump()
if hasattr(block, "model_dump")
else block
for block in response_content
],
}
else:
assistant_msg = {
"role": "assistant",
"content": content,
}
# Preserve provider metadata (provider-agnostic passthrough)
if hasattr(response, "metadata") and response.metadata:
assistant_msg["metadata"] = response.metadata
await context.add_message(assistant_msg)
except LLMError as e:
await hooks.emit(
PROVIDER_ERROR,
{
"provider": provider_name,
"error": {"type": type(e).__name__, "msg": str(e)},
"retryable": e.retryable,
"status_code": e.status_code,
},
)
logger.error(
f"Error getting final response after max iterations: {e}"
)
except Exception as e:
await hooks.emit(
PROVIDER_ERROR,
{
"provider": provider_name,
"error": {"type": type(e).__name__, "msg": str(e)},
},
)
logger.error(
f"Error getting final response after max iterations: {e}"
)
await hooks.emit(
PROMPT_COMPLETE,
{
"response_preview": (final_content or "")[:200],
"length": len(final_content or ""),
},
)
# Emit orchestrator complete event
await hooks.emit(
ORCHESTRATOR_COMPLETE,
{
"orchestrator": "loop-basic",
"turn_count": iteration,
"status": "success" if final_content else "incomplete",
},
)
return final_content
except asyncio.CancelledError:
execution_status = "cancelled"
raise
except Exception:
execution_status = "error"
raise
finally:
await hooks.emit(
EXECUTION_END, {"response": final_content, "status": execution_status}
)
def _select_provider(self, providers: dict[str, Any]) -> Any:
"""Select a provider based on priority."""
if not providers:
return None
# Collect providers with their priority (default priority is 100)
provider_list = []
for name, provider in providers.items():
# Try to get priority from provider's config or attributes
priority = 100 # Default priority
if hasattr(provider, "priority"):
priority = provider.priority
elif hasattr(provider, "config") and isinstance(provider.config, dict):
priority = provider.config.get("priority", 100)
provider_list.append((priority, name, provider))
# Sort by priority (lower number = higher priority)
provider_list.sort(key=lambda x: x[0])
# Return the highest priority provider
if provider_list:
return provider_list[0][2]
return None