forked from openai/openai-agents-python
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathturn_resolution.py
More file actions
1915 lines (1777 loc) · 74.5 KB
/
turn_resolution.py
File metadata and controls
1915 lines (1777 loc) · 74.5 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
from __future__ import annotations
import asyncio
import inspect
from collections.abc import Awaitable, Callable, Mapping, Sequence
from typing import Any, Literal, cast
from openai.types.responses import (
ResponseCompactionItem,
ResponseComputerToolCall,
ResponseCustomToolCall,
ResponseFileSearchToolCall,
ResponseFunctionShellToolCallOutput,
ResponseFunctionToolCall,
ResponseFunctionWebSearch,
ResponseOutputMessage,
)
from openai.types.responses.response_code_interpreter_tool_call import (
ResponseCodeInterpreterToolCall,
)
from openai.types.responses.response_output_item import (
ImageGenerationCall,
LocalShellCall,
McpApprovalRequest,
McpCall,
McpListTools,
)
from openai.types.responses.response_reasoning_item import ResponseReasoningItem
from .._mcp_tool_metadata import collect_mcp_list_tools_metadata
from .._tool_identity import (
build_function_tool_lookup_map,
get_function_tool_lookup_key,
get_function_tool_lookup_key_for_call,
get_function_tool_lookup_key_for_tool,
get_tool_call_namespace,
get_tool_call_qualified_name,
get_tool_call_trace_name,
normalize_tool_call_for_function_tool,
should_allow_bare_name_approval_alias,
)
from ..agent import Agent, ToolsToFinalOutputResult
from ..agent_output import AgentOutputSchemaBase
from ..agent_tool_state import get_agent_tool_state_scope, peek_agent_tool_run_result
from ..exceptions import ModelBehaviorError, UserError
from ..handoffs import Handoff, HandoffInputData, HandoffInputFilter, nest_handoff_history
from ..items import (
CompactionItem,
HandoffCallItem,
HandoffOutputItem,
ItemHelpers,
MCPApprovalRequestItem,
MCPListToolsItem,
MessageOutputItem,
ModelResponse,
ReasoningItem,
RunItem,
ToolApprovalItem,
ToolCallItem,
ToolCallOutputItem,
ToolSearchCallItem,
ToolSearchOutputItem,
TResponseInputItem,
coerce_tool_search_call_raw_item,
coerce_tool_search_output_raw_item,
)
from ..lifecycle import RunHooks
from ..logger import logger
from ..run_config import RunConfig
from ..run_context import AgentHookContext, RunContextWrapper, TContext
from ..run_state import RunState
from ..stream_events import StreamEvent
from ..tool import (
ApplyPatchTool,
ComputerTool,
CustomTool,
FunctionTool,
FunctionToolResult,
HostedMCPTool,
LocalShellTool,
ShellTool,
Tool,
ToolOrigin,
ToolOriginType,
get_function_tool_origin,
)
from ..tool_guardrails import ToolInputGuardrailResult, ToolOutputGuardrailResult
from ..tracing import SpanError, handoff_span
from ..util import _coro, _error_tracing
from ..util._approvals import evaluate_needs_approval_setting
from .agent_bindings import AgentBindings
from .items import (
REJECTION_MESSAGE,
apply_patch_rejection_item,
function_rejection_item,
shell_rejection_item,
)
from .run_steps import (
NOT_FINAL_OUTPUT,
NextStepFinalOutput,
NextStepHandoff,
NextStepInterruption,
NextStepRunAgain,
ProcessedResponse,
QueueCompleteSentinel,
SingleStepResult,
ToolRunApplyPatchCall,
ToolRunComputerAction,
ToolRunCustom,
ToolRunFunction,
ToolRunHandoff,
ToolRunLocalShellCall,
ToolRunMCPApprovalRequest,
ToolRunShellCall,
)
from .streaming import stream_step_items_to_queue
from .tool_execution import (
build_litellm_json_tool_call,
coerce_apply_patch_operations,
coerce_shell_call,
extract_apply_patch_call_id,
extract_shell_call_id,
extract_tool_call_id,
function_needs_approval,
get_mapping_or_attr,
index_approval_items_by_call_id,
is_apply_patch_name,
parse_apply_patch_custom_input,
parse_apply_patch_function_args,
process_hosted_mcp_approvals,
resolve_approval_rejection_message,
resolve_enabled_function_tools,
should_keep_hosted_mcp_item,
)
from .tool_planning import (
_append_mcp_callback_results,
_build_plan_for_fresh_turn,
_build_plan_for_resume_turn,
_build_tool_output_index,
_build_tool_result_items,
_collect_runs_by_approval,
_collect_tool_interruptions,
_dedupe_tool_call_items,
_execute_tool_plan,
_make_unique_item_appender,
_select_function_tool_runs_for_resume,
)
__all__ = [
"execute_final_output_step",
"execute_final_output",
"execute_handoffs",
"check_for_final_output_from_tools",
"process_model_response",
"execute_tools_and_side_effects",
"resolve_interrupted_turn",
"get_single_step_result_from_response",
"run_final_output_hooks",
]
async def _maybe_finalize_from_tool_results(
*,
public_agent: Agent[TContext],
original_input: str | list[TResponseInputItem],
new_response: ModelResponse,
pre_step_items: list[RunItem],
new_step_items: list[RunItem],
function_results: list[FunctionToolResult],
hooks: RunHooks[TContext],
context_wrapper: RunContextWrapper[TContext],
tool_input_guardrail_results: list[ToolInputGuardrailResult],
tool_output_guardrail_results: list[ToolOutputGuardrailResult],
) -> SingleStepResult | None:
check_tool_use = await check_for_final_output_from_tools(
public_agent, function_results, context_wrapper
)
if not check_tool_use.is_final_output:
return None
if not public_agent.output_type or public_agent.output_type is str:
check_tool_use.final_output = str(check_tool_use.final_output)
if check_tool_use.final_output is None:
logger.error(
"Model returned a final output of None. Not raising an error because we assume"
"you know what you're doing."
)
return await execute_final_output(
public_agent=public_agent,
original_input=original_input,
new_response=new_response,
pre_step_items=pre_step_items,
new_step_items=new_step_items,
final_output=check_tool_use.final_output,
hooks=hooks,
context_wrapper=context_wrapper,
tool_input_guardrail_results=tool_input_guardrail_results,
tool_output_guardrail_results=tool_output_guardrail_results,
)
async def run_final_output_hooks(
agent: Agent[TContext],
hooks: RunHooks[TContext],
context_wrapper: RunContextWrapper[TContext],
final_output: Any,
) -> None:
agent_hook_context = AgentHookContext(
context=context_wrapper.context,
usage=context_wrapper.usage,
_approvals=context_wrapper._approvals,
turn_input=context_wrapper.turn_input,
)
await asyncio.gather(
hooks.on_agent_end(agent_hook_context, agent, final_output),
agent.hooks.on_end(agent_hook_context, agent, final_output)
if agent.hooks
else _coro.noop_coroutine(),
)
async def execute_final_output_step(
*,
public_agent: Agent[Any],
original_input: str | list[TResponseInputItem],
new_response: ModelResponse,
pre_step_items: list[RunItem],
new_step_items: list[RunItem],
final_output: Any,
hooks: RunHooks[Any],
context_wrapper: RunContextWrapper[Any],
tool_input_guardrail_results: list[ToolInputGuardrailResult],
tool_output_guardrail_results: list[ToolOutputGuardrailResult],
run_final_output_hooks_fn: Callable[
[Agent[Any], RunHooks[Any], RunContextWrapper[Any], Any], Awaitable[None]
]
| None = None,
) -> SingleStepResult:
"""Finalize a turn once final output is known and run end hooks."""
final_output_hooks = run_final_output_hooks_fn or run_final_output_hooks
await final_output_hooks(public_agent, hooks, context_wrapper, final_output)
return SingleStepResult(
original_input=original_input,
model_response=new_response,
pre_step_items=pre_step_items,
new_step_items=new_step_items,
next_step=NextStepFinalOutput(final_output),
tool_input_guardrail_results=tool_input_guardrail_results,
tool_output_guardrail_results=tool_output_guardrail_results,
output_guardrail_results=[],
)
async def execute_final_output(
*,
public_agent: Agent[Any],
original_input: str | list[TResponseInputItem],
new_response: ModelResponse,
pre_step_items: list[RunItem],
new_step_items: list[RunItem],
final_output: Any,
hooks: RunHooks[Any],
context_wrapper: RunContextWrapper[Any],
tool_input_guardrail_results: list[ToolInputGuardrailResult],
tool_output_guardrail_results: list[ToolOutputGuardrailResult],
run_final_output_hooks_fn: Callable[
[Agent[Any], RunHooks[Any], RunContextWrapper[Any], Any], Awaitable[None]
]
| None = None,
) -> SingleStepResult:
"""Convenience wrapper to finalize a turn and run end hooks."""
return await execute_final_output_step(
public_agent=public_agent,
original_input=original_input,
new_response=new_response,
pre_step_items=pre_step_items,
new_step_items=new_step_items,
final_output=final_output,
hooks=hooks,
context_wrapper=context_wrapper,
tool_input_guardrail_results=tool_input_guardrail_results,
tool_output_guardrail_results=tool_output_guardrail_results,
run_final_output_hooks_fn=run_final_output_hooks_fn,
)
def _resolve_server_managed_handoff_behavior(
*,
handoff: Handoff[Any, Agent[Any]],
from_agent: Agent[Any],
to_agent: Agent[Any],
run_config: RunConfig,
server_manages_conversation: bool,
input_filter: HandoffInputFilter | None,
should_nest_history: bool,
) -> tuple[HandoffInputFilter | None, bool]:
if not server_manages_conversation:
return input_filter, should_nest_history
if input_filter is not None:
raise UserError(
"Server-managed conversations do not support handoff input filters. "
"Remove Handoff.input_filter or RunConfig.handoff_input_filter, "
"or disable conversation_id, previous_response_id, and auto_previous_response_id."
)
if not should_nest_history:
return input_filter, should_nest_history
logger.warning(
"Server-managed conversations do not support nest_handoff_history for handoff "
"%s -> %s. Disabling nested handoff history and continuing with delta-only input.",
from_agent.name,
to_agent.name,
)
return input_filter, False
async def execute_handoffs(
*,
public_agent: Agent[TContext],
original_input: str | list[TResponseInputItem],
pre_step_items: list[RunItem],
new_step_items: list[RunItem],
new_response: ModelResponse,
run_handoffs: list[ToolRunHandoff],
hooks: RunHooks[TContext],
context_wrapper: RunContextWrapper[TContext],
run_config: RunConfig,
server_manages_conversation: bool = False,
nest_handoff_history_fn: Callable[..., HandoffInputData] | None = None,
) -> SingleStepResult:
"""Execute a handoff and prepare the next turn for the new agent."""
def nest_history(data: HandoffInputData, mapper: Any | None = None) -> HandoffInputData:
if nest_handoff_history_fn is None:
return nest_handoff_history(data, history_mapper=mapper)
return nest_handoff_history_fn(data, mapper)
multiple_handoffs = len(run_handoffs) > 1
if multiple_handoffs:
output_message = "Multiple handoffs detected, ignoring this one."
new_step_items.extend(
[
ToolCallOutputItem(
output=output_message,
raw_item=ItemHelpers.tool_call_output_item(handoff.tool_call, output_message),
agent=public_agent,
)
for handoff in run_handoffs[1:]
]
)
actual_handoff = run_handoffs[0]
with handoff_span(from_agent=public_agent.name) as span_handoff:
handoff = actual_handoff.handoff
new_agent: Agent[Any] = await handoff.on_invoke_handoff(
context_wrapper, actual_handoff.tool_call.arguments
)
span_handoff.span_data.to_agent = new_agent.name
if multiple_handoffs:
requested_agents = [handoff.handoff.agent_name for handoff in run_handoffs]
span_handoff.set_error(
SpanError(
message="Multiple handoffs requested",
data={
"requested_agents": requested_agents,
},
)
)
new_step_items.append(
HandoffOutputItem(
agent=public_agent,
raw_item=ItemHelpers.tool_call_output_item(
actual_handoff.tool_call,
handoff.get_transfer_message(new_agent),
),
source_agent=public_agent,
target_agent=new_agent,
)
)
await asyncio.gather(
hooks.on_handoff(
context=context_wrapper,
from_agent=public_agent,
to_agent=new_agent,
),
(
public_agent.hooks.on_handoff(
context_wrapper,
agent=new_agent,
source=public_agent,
)
if public_agent.hooks
else _coro.noop_coroutine()
),
)
input_filter = handoff.input_filter or (
run_config.handoff_input_filter if run_config else None
)
handoff_nest_setting = handoff.nest_handoff_history
should_nest_history = (
handoff_nest_setting
if handoff_nest_setting is not None
else run_config.nest_handoff_history
)
input_filter, should_nest_history = _resolve_server_managed_handoff_behavior(
handoff=handoff,
from_agent=public_agent,
to_agent=new_agent,
run_config=run_config,
server_manages_conversation=server_manages_conversation,
input_filter=input_filter,
should_nest_history=should_nest_history,
)
handoff_input_data: HandoffInputData | None = None
session_step_items: list[RunItem] | None = None
if input_filter or should_nest_history:
handoff_input_data = HandoffInputData(
input_history=tuple(original_input)
if isinstance(original_input, list)
else original_input,
pre_handoff_items=tuple(pre_step_items),
new_items=tuple(new_step_items),
run_context=context_wrapper,
)
if input_filter and handoff_input_data is not None:
filter_name = getattr(input_filter, "__qualname__", repr(input_filter))
from_agent = getattr(public_agent, "name", public_agent.__class__.__name__)
to_agent = getattr(new_agent, "name", new_agent.__class__.__name__)
logger.debug(
"Filtering handoff inputs with %s for %s -> %s",
filter_name,
from_agent,
to_agent,
)
if not callable(input_filter):
_error_tracing.attach_error_to_span(
span_handoff,
SpanError(
message="Invalid input filter",
data={"details": "not callable()"},
),
)
raise UserError(f"Invalid input filter: {input_filter}")
filtered = input_filter(handoff_input_data)
if inspect.isawaitable(filtered):
filtered = await filtered
if not isinstance(filtered, HandoffInputData):
_error_tracing.attach_error_to_span(
span_handoff,
SpanError(
message="Invalid input filter result",
data={"details": "not a HandoffInputData"},
),
)
raise UserError(f"Invalid input filter result: {filtered}")
original_input = (
filtered.input_history
if isinstance(filtered.input_history, str)
else list(filtered.input_history)
)
pre_step_items = list(filtered.pre_handoff_items)
new_step_items = list(filtered.new_items)
# For custom input filters, keep full new_items for session history and
# use input_items for model input when provided.
if filtered.input_items is not None:
session_step_items = list(filtered.new_items)
new_step_items = list(filtered.input_items)
else:
session_step_items = None
elif should_nest_history and handoff_input_data is not None:
nested = nest_history(handoff_input_data, run_config.handoff_history_mapper)
original_input = (
nested.input_history
if isinstance(nested.input_history, str)
else list(nested.input_history)
)
pre_step_items = list(nested.pre_handoff_items)
# Keep full new_items for session history.
session_step_items = list(nested.new_items)
# Use input_items (filtered) for model input if available.
if nested.input_items is not None:
new_step_items = list(nested.input_items)
else:
new_step_items = session_step_items
else:
# No filtering or nesting - session_step_items not needed.
session_step_items = None
return SingleStepResult(
original_input=original_input,
model_response=new_response,
pre_step_items=pre_step_items,
new_step_items=new_step_items,
next_step=NextStepHandoff(new_agent),
tool_input_guardrail_results=[],
tool_output_guardrail_results=[],
session_step_items=session_step_items,
)
async def check_for_final_output_from_tools(
agent: Agent[TContext],
tool_results: list[FunctionToolResult],
context_wrapper: RunContextWrapper[TContext],
) -> ToolsToFinalOutputResult:
"""Determine if tool results should produce a final output."""
if not tool_results:
return NOT_FINAL_OUTPUT
if agent.tool_use_behavior == "run_llm_again":
return NOT_FINAL_OUTPUT
elif agent.tool_use_behavior == "stop_on_first_tool":
return ToolsToFinalOutputResult(is_final_output=True, final_output=tool_results[0].output)
elif isinstance(agent.tool_use_behavior, dict):
names = agent.tool_use_behavior.get("stop_at_tool_names", [])
for tool_result in tool_results:
if tool_result.tool.name in names or tool_result.tool.qualified_name in names:
return ToolsToFinalOutputResult(
is_final_output=True, final_output=tool_result.output
)
return ToolsToFinalOutputResult(is_final_output=False, final_output=None)
elif callable(agent.tool_use_behavior):
if inspect.iscoroutinefunction(agent.tool_use_behavior):
return await cast(
Awaitable[ToolsToFinalOutputResult],
agent.tool_use_behavior(context_wrapper, tool_results),
)
return cast(
ToolsToFinalOutputResult, agent.tool_use_behavior(context_wrapper, tool_results)
)
logger.error("Invalid tool_use_behavior: %s", agent.tool_use_behavior)
raise UserError(f"Invalid tool_use_behavior: {agent.tool_use_behavior}")
async def execute_tools_and_side_effects(
*,
bindings: AgentBindings[TContext],
original_input: str | list[TResponseInputItem],
pre_step_items: list[RunItem],
new_response: ModelResponse,
processed_response: ProcessedResponse,
output_schema: AgentOutputSchemaBase | None,
hooks: RunHooks[TContext],
context_wrapper: RunContextWrapper[TContext],
run_config: RunConfig,
server_manages_conversation: bool = False,
) -> SingleStepResult:
"""Run one turn of the loop, coordinating tools, approvals, guardrails, and handoffs."""
public_agent = bindings.public_agent
execute_final_output_call = execute_final_output
execute_handoffs_call = execute_handoffs
pre_step_items = list(pre_step_items)
approval_items_by_call_id = index_approval_items_by_call_id(pre_step_items)
plan = _build_plan_for_fresh_turn(
processed_response=processed_response,
agent=public_agent,
context_wrapper=context_wrapper,
approval_items_by_call_id=approval_items_by_call_id,
)
new_step_items = _dedupe_tool_call_items(
existing_items=pre_step_items,
new_items=processed_response.new_items,
)
(
function_results,
tool_input_guardrail_results,
tool_output_guardrail_results,
computer_results,
custom_tool_results,
shell_results,
apply_patch_results,
local_shell_results,
) = await _execute_tool_plan(
plan=plan,
bindings=bindings,
hooks=hooks,
context_wrapper=context_wrapper,
run_config=run_config,
)
new_step_items.extend(
_build_tool_result_items(
function_results=function_results,
computer_results=computer_results,
custom_tool_results=custom_tool_results,
shell_results=shell_results,
apply_patch_results=apply_patch_results,
local_shell_results=local_shell_results,
)
)
interruptions = _collect_tool_interruptions(
function_results=function_results,
custom_tool_results=custom_tool_results,
shell_results=shell_results,
apply_patch_results=apply_patch_results,
)
if plan.approved_mcp_responses:
new_step_items.extend(plan.approved_mcp_responses)
if plan.pending_interruptions:
interruptions.extend(plan.pending_interruptions)
new_step_items.extend(plan.pending_interruptions)
processed_response.interruptions = interruptions
if interruptions:
return SingleStepResult(
original_input=original_input,
model_response=new_response,
pre_step_items=pre_step_items,
new_step_items=new_step_items,
next_step=NextStepInterruption(interruptions=interruptions),
tool_input_guardrail_results=tool_input_guardrail_results,
tool_output_guardrail_results=tool_output_guardrail_results,
processed_response=processed_response,
)
await _append_mcp_callback_results(
agent=public_agent,
requests=plan.mcp_requests_with_callback,
context_wrapper=context_wrapper,
append_item=new_step_items.append,
)
if run_handoffs := processed_response.handoffs:
return await execute_handoffs_call(
public_agent=public_agent,
original_input=original_input,
pre_step_items=pre_step_items,
new_step_items=new_step_items,
new_response=new_response,
run_handoffs=run_handoffs,
hooks=hooks,
context_wrapper=context_wrapper,
run_config=run_config,
server_manages_conversation=server_manages_conversation,
)
tool_final_output = await _maybe_finalize_from_tool_results(
public_agent=public_agent,
original_input=original_input,
new_response=new_response,
pre_step_items=pre_step_items,
new_step_items=new_step_items,
function_results=function_results,
hooks=hooks,
context_wrapper=context_wrapper,
tool_input_guardrail_results=tool_input_guardrail_results,
tool_output_guardrail_results=tool_output_guardrail_results,
)
if tool_final_output is not None:
return tool_final_output
message_items = [item for item in new_step_items if isinstance(item, MessageOutputItem)]
potential_final_output_text = (
ItemHelpers.extract_text(message_items[-1].raw_item) if message_items else None
)
if not processed_response.has_tools_or_approvals_to_run():
has_tool_activity_without_message = not message_items and bool(
processed_response.tools_used
)
if not has_tool_activity_without_message:
if output_schema and not output_schema.is_plain_text() and potential_final_output_text:
final_output = output_schema.validate_json(potential_final_output_text)
return await execute_final_output_call(
public_agent=public_agent,
original_input=original_input,
new_response=new_response,
pre_step_items=pre_step_items,
new_step_items=new_step_items,
final_output=final_output,
hooks=hooks,
context_wrapper=context_wrapper,
tool_input_guardrail_results=tool_input_guardrail_results,
tool_output_guardrail_results=tool_output_guardrail_results,
)
if not output_schema or output_schema.is_plain_text():
return await execute_final_output_call(
public_agent=public_agent,
original_input=original_input,
new_response=new_response,
pre_step_items=pre_step_items,
new_step_items=new_step_items,
final_output=potential_final_output_text or "",
hooks=hooks,
context_wrapper=context_wrapper,
tool_input_guardrail_results=tool_input_guardrail_results,
tool_output_guardrail_results=tool_output_guardrail_results,
)
return SingleStepResult(
original_input=original_input,
model_response=new_response,
pre_step_items=pre_step_items,
new_step_items=new_step_items,
next_step=NextStepRunAgain(),
tool_input_guardrail_results=tool_input_guardrail_results,
tool_output_guardrail_results=tool_output_guardrail_results,
)
async def resolve_interrupted_turn(
*,
bindings: AgentBindings[TContext],
original_input: str | list[TResponseInputItem],
original_pre_step_items: list[RunItem],
new_response: ModelResponse,
processed_response: ProcessedResponse,
hooks: RunHooks[TContext],
context_wrapper: RunContextWrapper[TContext],
run_config: RunConfig,
server_manages_conversation: bool = False,
run_state: RunState | None = None,
nest_handoff_history_fn: Callable[..., HandoffInputData] | None = None,
) -> SingleStepResult:
"""Continue a turn that was previously interrupted waiting for tool approval."""
public_agent = bindings.public_agent
execution_agent = bindings.execution_agent
execute_handoffs_call = execute_handoffs
def nest_history(data: HandoffInputData, mapper: Any | None = None) -> HandoffInputData:
if nest_handoff_history_fn is None:
return nest_handoff_history(data, history_mapper=mapper)
return nest_handoff_history_fn(data, mapper)
def _pending_approvals_from_state() -> list[ToolApprovalItem]:
if (
run_state is not None
and hasattr(run_state, "_current_step")
and isinstance(run_state._current_step, NextStepInterruption)
):
return [
item
for item in run_state._current_step.interruptions
if isinstance(item, ToolApprovalItem)
]
return [item for item in original_pre_step_items if isinstance(item, ToolApprovalItem)]
async def _record_function_rejection(
call_id: str | None,
tool_call: ResponseFunctionToolCall,
function_tool: FunctionTool,
) -> None:
if isinstance(call_id, str) and call_id in rejected_function_call_ids:
return
rejection_message = REJECTION_MESSAGE
if call_id:
tool_namespace = get_tool_call_namespace(tool_call)
rejection_message = await resolve_approval_rejection_message(
context_wrapper=context_wrapper,
run_config=run_config,
tool_type="function",
tool_name=get_tool_call_trace_name(tool_call) or function_tool.name,
call_id=call_id,
tool_namespace=tool_namespace,
tool_lookup_key=get_function_tool_lookup_key_for_tool(function_tool),
existing_pending=approval_items_by_call_id.get(call_id),
)
rejected_function_outputs.append(
function_rejection_item(
public_agent,
tool_call,
rejection_message=rejection_message,
scope_id=tool_state_scope_id,
tool_origin=get_function_tool_origin(function_tool),
)
)
if isinstance(call_id, str):
rejected_function_call_ids.add(call_id)
async def _function_requires_approval(run: ToolRunFunction) -> bool:
call_id = run.tool_call.call_id
if call_id and call_id in approval_items_by_call_id:
return True
try:
return await function_needs_approval(
run.function_tool,
context_wrapper,
run.tool_call,
)
except UserError:
raise
except Exception:
return True
try:
context_wrapper.turn_input = ItemHelpers.input_to_new_input_list(original_input)
except Exception:
context_wrapper.turn_input = []
pending_approval_items = _pending_approvals_from_state()
approval_items_by_call_id = index_approval_items_by_call_id(pending_approval_items)
tool_state_scope_id = get_agent_tool_state_scope(context_wrapper)
rejected_function_outputs: list[RunItem] = []
rejected_function_call_ids: set[str] = set()
rerun_function_call_ids: set[str] = set()
pending_interruptions: list[ToolApprovalItem] = []
pending_interruption_keys: set[str] = set()
output_index = _build_tool_output_index(original_pre_step_items)
def _has_output_item(call_id: str, expected_type: str) -> bool:
return (expected_type, call_id) in output_index
def _shell_call_id_from_run(run: ToolRunShellCall) -> str:
return extract_shell_call_id(run.tool_call)
def _apply_patch_call_id_from_run(run: ToolRunApplyPatchCall) -> str:
return extract_apply_patch_call_id(run.tool_call)
def _custom_call_id_from_run(run: ToolRunCustom) -> str:
call_id = extract_tool_call_id(run.tool_call)
if not call_id:
raise ModelBehaviorError("Custom tool call is missing call_id.")
return call_id
def _computer_call_id_from_run(run: ToolRunComputerAction) -> str:
call_id = extract_tool_call_id(run.tool_call)
if not call_id:
raise ModelBehaviorError("Computer action is missing call_id.")
return call_id
def _shell_tool_name(run: ToolRunShellCall) -> str:
return run.shell_tool.name
def _apply_patch_tool_name(run: ToolRunApplyPatchCall) -> str:
return run.apply_patch_tool.name
def _custom_tool_name(run: ToolRunCustom) -> str:
return run.custom_tool.name
async def _build_shell_rejection(run: ToolRunShellCall, call_id: str) -> RunItem:
rejection_message = await resolve_approval_rejection_message(
context_wrapper=context_wrapper,
run_config=run_config,
tool_type="shell",
tool_name=run.shell_tool.name,
call_id=call_id,
)
return cast(
RunItem,
shell_rejection_item(
public_agent,
call_id,
rejection_message=rejection_message,
),
)
async def _build_apply_patch_rejection(run: ToolRunApplyPatchCall, call_id: str) -> RunItem:
rejection_message = await resolve_approval_rejection_message(
context_wrapper=context_wrapper,
run_config=run_config,
tool_type="apply_patch",
tool_name=run.apply_patch_tool.name,
call_id=call_id,
)
return cast(
RunItem,
apply_patch_rejection_item(
public_agent,
call_id,
output_type="apply_patch_call_output",
rejection_message=rejection_message,
),
)
async def _build_custom_rejection(run: ToolRunCustom, call_id: str) -> RunItem:
rejection_message = await resolve_approval_rejection_message(
context_wrapper=context_wrapper,
run_config=run_config,
tool_type="custom",
tool_name=run.custom_tool.name,
call_id=call_id,
)
return ToolCallOutputItem(
agent=public_agent,
output=rejection_message,
raw_item=cast(
Any,
{
"type": "custom_tool_call_output",
"call_id": call_id,
"output": rejection_message,
},
),
)
async def _shell_needs_approval(run: ToolRunShellCall) -> bool:
shell_call = coerce_shell_call(run.tool_call)
return await evaluate_needs_approval_setting(
run.shell_tool.needs_approval,
context_wrapper,
shell_call.action,
shell_call.call_id,
)
async def _apply_patch_needs_approval(run: ToolRunApplyPatchCall) -> bool:
operations = coerce_apply_patch_operations(
run.tool_call,
context_wrapper=context_wrapper,
)
call_id = extract_apply_patch_call_id(run.tool_call)
for operation in operations:
if await evaluate_needs_approval_setting(
run.apply_patch_tool.needs_approval, context_wrapper, operation, call_id
):
return True
return False
async def _custom_tool_needs_approval(run: ToolRunCustom) -> bool:
tool_input = get_mapping_or_attr(run.tool_call, "input")
call_id = _custom_call_id_from_run(run)
if not isinstance(tool_input, str):
raise ModelBehaviorError("Custom tool call is missing input.")
return await evaluate_needs_approval_setting(
run.custom_tool.runtime_needs_approval(),
context_wrapper,
tool_input,
call_id,
)
def _shell_output_exists(call_id: str) -> bool:
return _has_output_item(call_id, "shell_call_output")
def _apply_patch_output_exists(call_id: str) -> bool:
return _has_output_item(call_id, "apply_patch_call_output")
def _custom_tool_output_exists(call_id: str) -> bool:
return _has_output_item(call_id, "custom_tool_call_output")
def _computer_output_exists(call_id: str) -> bool:
return _has_output_item(call_id, "computer_call_output")
def _nested_interruptions_status(
interruptions: Sequence[ToolApprovalItem],
) -> Literal["approved", "pending", "rejected"]:
has_pending = False
for interruption in interruptions:
call_id = extract_tool_call_id(interruption.raw_item)
if not call_id:
has_pending = True
continue
status = context_wrapper.get_approval_status(
interruption.tool_name or "",
call_id,
tool_namespace=interruption.tool_namespace,
existing_pending=interruption,
)
if status is False:
return "rejected"
if status is None:
has_pending = True
return "pending" if has_pending else "approved"
def _function_output_exists(run: ToolRunFunction) -> bool:
call_id = extract_tool_call_id(run.tool_call)
if not call_id:
return False
pending_run_result = peek_agent_tool_run_result(
run.tool_call,
scope_id=tool_state_scope_id,
)
if pending_run_result and getattr(pending_run_result, "interruptions", None):
status = _nested_interruptions_status(pending_run_result.interruptions)
if status in ("approved", "rejected"):
rerun_function_call_ids.add(call_id)
return False
return True
return _has_output_item(call_id, "function_call_output")
def _add_pending_interruption(item: ToolApprovalItem | None) -> None:
if item is None:
return
call_id = extract_tool_call_id(item.raw_item)
key = call_id or f"raw:{id(item.raw_item)}"
if key in pending_interruption_keys:
return
pending_interruption_keys.add(key)