-
Notifications
You must be signed in to change notification settings - Fork 3.7k
Expand file tree
/
Copy pathrun.py
More file actions
1863 lines (1737 loc) · 90.4 KB
/
run.py
File metadata and controls
1863 lines (1737 loc) · 90.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
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 contextlib
import warnings
from typing import cast
from typing_extensions import Unpack
from . import _debug
from ._tool_identity import get_tool_trace_name_for_tool
from .agent import Agent
from .agent_tool_state import set_agent_tool_state_scope
from .exceptions import (
AgentsException,
InputGuardrailTripwireTriggered,
MaxTurnsExceeded,
RunErrorDetails,
UserError,
)
from .guardrail import (
InputGuardrailResult,
)
from .items import (
ItemHelpers,
RunItem,
TResponseInputItem,
)
from .lifecycle import RunHooks
from .logger import logger
from .memory import Session
from .result import RunResult, RunResultStreaming
from .run_config import (
DEFAULT_MAX_TURNS,
CallModelData,
CallModelInputFilter,
ModelInputData,
ReasoningItemIdPolicy,
RunConfig,
RunOptions,
ToolErrorFormatter,
ToolErrorFormatterArgs,
)
from .run_context import RunContextWrapper, TContext
from .run_error_handlers import RunErrorHandlers
from .run_internal.agent_bindings import bind_public_agent
from .run_internal.agent_runner_helpers import (
append_model_response_if_new,
apply_resumed_conversation_settings,
attach_usage_to_span,
build_interruption_result,
build_resumed_stream_debug_extra,
ensure_context_wrapper,
finalize_conversation_tracking,
input_guardrails_triggered,
resolve_processed_response,
resolve_resumed_context,
resolve_trace_settings,
save_turn_items_if_needed,
should_cancel_parallel_model_task_on_input_guardrail_trip,
snapshot_usage,
update_run_state_for_interruption,
usage_delta,
validate_session_conversation_settings,
)
from .run_internal.approvals import approvals_from_step
from .run_internal.error_handlers import (
build_run_error_data,
create_message_output_item,
format_final_output_text,
resolve_run_error_handler_result,
validate_handler_final_output,
)
from .run_internal.items import (
copy_input_items,
normalize_resumed_input,
)
from .run_internal.oai_conversation import OpenAIServerConversationTracker
from .run_internal.prompt_cache_key import PromptCacheKeyResolver
from .run_internal.run_grouping import resolve_run_grouping_id
from .run_internal.run_loop import (
get_all_tools,
get_handoffs,
get_output_schema,
initialize_computer_tools,
resolve_interrupted_turn,
run_final_output_hooks,
run_input_guardrails,
run_output_guardrails,
run_single_turn,
start_streaming,
validate_run_hooks,
)
from .run_internal.run_steps import (
NextStepFinalOutput,
NextStepHandoff,
NextStepInterruption,
NextStepRunAgain,
)
from .run_internal.session_persistence import (
persist_session_items_for_guardrail_trip,
prepare_input_with_session,
resumed_turn_items,
save_result_to_session,
save_resumed_turn_items,
session_items_for_turn,
update_run_state_after_resume,
)
from .run_internal.tool_use_tracker import (
AgentToolUseTracker,
hydrate_tool_use_tracker,
serialize_tool_use_tracker,
)
from .run_state import RunState
from .sandbox.memory.rollouts import terminal_metadata_for_exception
from .sandbox.runtime import SandboxRuntime
from .tool import dispose_resolved_computers
from .tool_guardrails import ToolInputGuardrailResult, ToolOutputGuardrailResult
from .tracing import Span, SpanError, agent_span, get_current_trace, task_span, turn_span
from .tracing.context import TraceCtxManager, create_trace_for_run
from .tracing.span_data import AgentSpanData, TaskSpanData
from .util import _error_tracing
DEFAULT_AGENT_RUNNER: AgentRunner = None # type: ignore
# the value is set at the end of the module
__all__ = [
"AgentRunner",
"Runner",
"RunConfig",
"RunOptions",
"RunState",
"RunContextWrapper",
"ModelInputData",
"CallModelData",
"CallModelInputFilter",
"ReasoningItemIdPolicy",
"ToolErrorFormatter",
"ToolErrorFormatterArgs",
"DEFAULT_MAX_TURNS",
"set_default_agent_runner",
"get_default_agent_runner",
]
def set_default_agent_runner(runner: AgentRunner | None) -> None:
"""
WARNING: this class is experimental and not part of the public API
It should not be used directly.
"""
global DEFAULT_AGENT_RUNNER
DEFAULT_AGENT_RUNNER = runner or AgentRunner()
def get_default_agent_runner() -> AgentRunner:
"""
WARNING: this class is experimental and not part of the public API
It should not be used directly.
"""
global DEFAULT_AGENT_RUNNER
return DEFAULT_AGENT_RUNNER
def _sandbox_memory_rollout_id(
*,
run_config: RunConfig,
conversation_id: str | None,
session: Session | None,
) -> str | None:
if run_config.sandbox is None:
return None
return resolve_run_grouping_id(
conversation_id=conversation_id,
session=session,
group_id=run_config.group_id,
)
def _sandbox_memory_input(
*,
memory_input_items_for_persistence: list[TResponseInputItem] | None,
original_user_input: str | list[TResponseInputItem] | None,
original_input: str | list[TResponseInputItem],
) -> str | list[TResponseInputItem]:
if memory_input_items_for_persistence is not None:
return list(memory_input_items_for_persistence)
if original_user_input is not None:
return copy_input_items(original_user_input)
return copy_input_items(original_input)
class Runner:
@classmethod
async def run(
cls,
starting_agent: Agent[TContext],
input: str | list[TResponseInputItem] | RunState[TContext],
*,
context: TContext | None = None,
max_turns: int = DEFAULT_MAX_TURNS,
hooks: RunHooks[TContext] | None = None,
run_config: RunConfig | None = None,
error_handlers: RunErrorHandlers[TContext] | None = None,
previous_response_id: str | None = None,
auto_previous_response_id: bool = False,
conversation_id: str | None = None,
session: Session | None = None,
) -> RunResult:
"""
Run a workflow starting at the given agent.
The agent will run in a loop until a final output is generated. The loop runs like so:
1. The agent is invoked with the given input.
2. If there is a final output (i.e. the agent produces something of type
`agent.output_type`), the loop terminates.
3. If there's a handoff, we run the loop again, with the new agent.
4. Else, we run tool calls (if any), and re-run the loop.
In two cases, the agent may raise an exception:
1. If the max_turns is exceeded, a MaxTurnsExceeded exception is raised unless handled.
2. If a guardrail tripwire is triggered, a GuardrailTripwireTriggered
exception is raised.
Note:
Only the first agent's input guardrails are run.
Args:
starting_agent: The starting agent to run.
input: The initial input to the agent. You can pass a single string for a
user message, or a list of input items.
context: The context to run the agent with.
max_turns: The maximum number of turns to run the agent for. A turn is
defined as one AI invocation (including any tool calls that might occur).
hooks: An object that receives callbacks on various lifecycle events.
run_config: Global settings for the entire agent run.
error_handlers: Error handlers keyed by error kind. Currently supports max_turns.
previous_response_id: The ID of the previous response. If using OpenAI
models via the Responses API, this allows you to skip passing in input
from the previous turn.
conversation_id: The conversation ID
(https://platform.openai.com/docs/guides/conversation-state?api-mode=responses).
If provided, the conversation will be used to read and write items.
Every agent will have access to the conversation history so far,
and its output items will be written to the conversation.
We recommend only using this if you are exclusively using OpenAI models;
other model providers don't write to the Conversation object,
so you'll end up having partial conversations stored.
session: A session for automatic conversation history management.
Returns:
A run result containing all the inputs, guardrail results and the output of
the last agent. Agents may perform handoffs, so we don't know the specific
type of the output.
"""
runner = DEFAULT_AGENT_RUNNER
return await runner.run(
starting_agent,
input,
context=context,
max_turns=max_turns,
hooks=hooks,
run_config=run_config,
error_handlers=error_handlers,
previous_response_id=previous_response_id,
auto_previous_response_id=auto_previous_response_id,
conversation_id=conversation_id,
session=session,
)
@classmethod
def run_sync(
cls,
starting_agent: Agent[TContext],
input: str | list[TResponseInputItem] | RunState[TContext],
*,
context: TContext | None = None,
max_turns: int = DEFAULT_MAX_TURNS,
hooks: RunHooks[TContext] | None = None,
run_config: RunConfig | None = None,
error_handlers: RunErrorHandlers[TContext] | None = None,
previous_response_id: str | None = None,
auto_previous_response_id: bool = False,
conversation_id: str | None = None,
session: Session | None = None,
) -> RunResult:
"""
Run a workflow synchronously, starting at the given agent.
Note:
This just wraps the `run` method, so it will not work if there's already an
event loop (e.g. inside an async function, or in a Jupyter notebook or async
context like FastAPI). For those cases, use the `run` method instead.
The agent will run in a loop until a final output is generated. The loop runs:
1. The agent is invoked with the given input.
2. If there is a final output (i.e. the agent produces something of type
`agent.output_type`), the loop terminates.
3. If there's a handoff, we run the loop again, with the new agent.
4. Else, we run tool calls (if any), and re-run the loop.
In two cases, the agent may raise an exception:
1. If the max_turns is exceeded, a MaxTurnsExceeded exception is raised unless handled.
2. If a guardrail tripwire is triggered, a GuardrailTripwireTriggered
exception is raised.
Note:
Only the first agent's input guardrails are run.
Args:
starting_agent: The starting agent to run.
input: The initial input to the agent. You can pass a single string for a
user message, or a list of input items.
context: The context to run the agent with.
max_turns: The maximum number of turns to run the agent for. A turn is
defined as one AI invocation (including any tool calls that might occur).
hooks: An object that receives callbacks on various lifecycle events.
run_config: Global settings for the entire agent run.
error_handlers: Error handlers keyed by error kind. Currently supports max_turns.
previous_response_id: The ID of the previous response, if using OpenAI
models via the Responses API, this allows you to skip passing in input
from the previous turn.
conversation_id: The ID of the stored conversation, if any.
session: A session for automatic conversation history management.
Returns:
A run result containing all the inputs, guardrail results and the output of
the last agent. Agents may perform handoffs, so we don't know the specific
type of the output.
"""
runner = DEFAULT_AGENT_RUNNER
return runner.run_sync(
starting_agent,
input,
context=context,
max_turns=max_turns,
hooks=hooks,
run_config=run_config,
error_handlers=error_handlers,
previous_response_id=previous_response_id,
conversation_id=conversation_id,
session=session,
auto_previous_response_id=auto_previous_response_id,
)
@classmethod
def run_streamed(
cls,
starting_agent: Agent[TContext],
input: str | list[TResponseInputItem] | RunState[TContext],
context: TContext | None = None,
max_turns: int = DEFAULT_MAX_TURNS,
hooks: RunHooks[TContext] | None = None,
run_config: RunConfig | None = None,
previous_response_id: str | None = None,
auto_previous_response_id: bool = False,
conversation_id: str | None = None,
session: Session | None = None,
*,
error_handlers: RunErrorHandlers[TContext] | None = None,
) -> RunResultStreaming:
"""
Run a workflow starting at the given agent in streaming mode.
The returned result object contains a method you can use to stream semantic
events as they are generated.
The agent will run in a loop until a final output is generated. The loop runs like so:
1. The agent is invoked with the given input.
2. If there is a final output (i.e. the agent produces something of type
`agent.output_type`), the loop terminates.
3. If there's a handoff, we run the loop again, with the new agent.
4. Else, we run tool calls (if any), and re-run the loop.
In two cases, the agent may raise an exception:
1. If the max_turns is exceeded, a MaxTurnsExceeded exception is raised unless handled.
2. If a guardrail tripwire is triggered, a GuardrailTripwireTriggered
exception is raised.
Note:
Only the first agent's input guardrails are run.
Args:
starting_agent: The starting agent to run.
input: The initial input to the agent. You can pass a single string for a
user message, or a list of input items.
context: The context to run the agent with.
max_turns: The maximum number of turns to run the agent for. A turn is
defined as one AI invocation (including any tool calls that might occur).
hooks: An object that receives callbacks on various lifecycle events.
run_config: Global settings for the entire agent run.
error_handlers: Error handlers keyed by error kind. Currently supports max_turns.
previous_response_id: The ID of the previous response, if using OpenAI
models via the Responses API, this allows you to skip passing in input
from the previous turn.
conversation_id: The ID of the stored conversation, if any.
session: A session for automatic conversation history management.
Returns:
A result object that contains data about the run, as well as a method to
stream events.
"""
runner = DEFAULT_AGENT_RUNNER
return runner.run_streamed(
starting_agent,
input,
context=context,
max_turns=max_turns,
hooks=hooks,
run_config=run_config,
error_handlers=error_handlers,
previous_response_id=previous_response_id,
auto_previous_response_id=auto_previous_response_id,
conversation_id=conversation_id,
session=session,
)
class AgentRunner:
"""
WARNING: this class is experimental and not part of the public API
It should not be used directly or subclassed.
"""
async def run(
self,
starting_agent: Agent[TContext],
input: str | list[TResponseInputItem] | RunState[TContext],
**kwargs: Unpack[RunOptions[TContext]],
) -> RunResult:
context = kwargs.get("context")
max_turns = kwargs.get("max_turns", DEFAULT_MAX_TURNS)
hooks = cast(RunHooks[TContext], validate_run_hooks(kwargs.get("hooks")))
run_config = kwargs.get("run_config")
error_handlers = kwargs.get("error_handlers")
previous_response_id = kwargs.get("previous_response_id")
auto_previous_response_id = kwargs.get("auto_previous_response_id", False)
conversation_id = kwargs.get("conversation_id")
session = kwargs.get("session")
if run_config is None:
run_config = RunConfig()
is_resumed_state = isinstance(input, RunState)
run_state: RunState[TContext] | None = None
starting_input = input if not is_resumed_state else None
original_user_input: str | list[TResponseInputItem] | None = None
session_input_items_for_persistence: list[TResponseInputItem] | None = (
[] if (session is not None and is_resumed_state) else None
)
# Track the most recent input batch we persisted so conversation-lock retries can rewind
# exactly those items (and not the full history).
last_saved_input_snapshot_for_rewind: list[TResponseInputItem] | None = None
if is_resumed_state:
run_state = cast(RunState[TContext], input)
(
conversation_id,
previous_response_id,
auto_previous_response_id,
) = apply_resumed_conversation_settings(
run_state=run_state,
conversation_id=conversation_id,
previous_response_id=previous_response_id,
auto_previous_response_id=auto_previous_response_id,
)
validate_session_conversation_settings(
session,
conversation_id=conversation_id,
previous_response_id=previous_response_id,
auto_previous_response_id=auto_previous_response_id,
)
starting_input = run_state._original_input
original_user_input = copy_input_items(run_state._original_input)
prepared_input = normalize_resumed_input(original_user_input)
context_wrapper = resolve_resumed_context(
run_state=run_state,
context=context,
)
context = context_wrapper.context
max_turns = run_state._max_turns
else:
raw_input = cast(str | list[TResponseInputItem], input)
original_user_input = raw_input
validate_session_conversation_settings(
session,
conversation_id=conversation_id,
previous_response_id=previous_response_id,
auto_previous_response_id=auto_previous_response_id,
)
server_manages_conversation = (
conversation_id is not None
or previous_response_id is not None
or auto_previous_response_id
)
if server_manages_conversation:
prepared_input, _ = await prepare_input_with_session(
raw_input,
session,
run_config.session_input_callback,
run_config.session_settings,
include_history_in_prepared_input=False,
preserve_dropped_new_items=True,
)
original_input_for_state = raw_input
session_input_items_for_persistence = []
else:
(
prepared_input,
session_input_items_for_persistence,
) = await prepare_input_with_session(
raw_input,
session,
run_config.session_input_callback,
run_config.session_settings,
)
original_input_for_state = prepared_input
resolved_reasoning_item_id_policy: ReasoningItemIdPolicy | None = (
run_config.reasoning_item_id_policy
if run_config.reasoning_item_id_policy is not None
else (run_state._reasoning_item_id_policy if run_state is not None else None)
)
if run_state is not None:
run_state._reasoning_item_id_policy = resolved_reasoning_item_id_policy
# Check whether to enable OpenAI server-managed conversation
if (
conversation_id is not None
or previous_response_id is not None
or auto_previous_response_id
):
server_conversation_tracker = OpenAIServerConversationTracker(
conversation_id=conversation_id,
previous_response_id=previous_response_id,
auto_previous_response_id=auto_previous_response_id,
reasoning_item_id_policy=resolved_reasoning_item_id_policy,
)
else:
server_conversation_tracker = None
session_persistence_enabled = session is not None and server_conversation_tracker is None
memory_input_items_for_persistence = (
list(session_input_items_for_persistence)
if session_persistence_enabled and session_input_items_for_persistence is not None
else None
)
if server_conversation_tracker is not None and is_resumed_state and run_state is not None:
session_input_items: list[TResponseInputItem] | None = None
if session is not None:
try:
session_input_items = await session.get_items()
except Exception:
session_input_items = None
server_conversation_tracker.hydrate_from_state(
original_input=run_state._original_input,
generated_items=run_state._generated_items,
model_responses=run_state._model_responses,
session_items=session_input_items,
)
tool_use_tracker = AgentToolUseTracker()
if is_resumed_state and run_state is not None:
hydrate_tool_use_tracker(tool_use_tracker, run_state, starting_agent)
(
trace_workflow_name,
trace_id,
trace_group_id,
trace_metadata,
trace_config,
) = resolve_trace_settings(run_state=run_state, run_config=run_config)
with TraceCtxManager(
workflow_name=trace_workflow_name,
trace_id=trace_id,
group_id=trace_group_id,
metadata=trace_metadata,
tracing=trace_config,
disabled=run_config.tracing_disabled,
trace_state=run_state._trace_state if run_state is not None else None,
reattach_resumed_trace=is_resumed_state,
):
if is_resumed_state and run_state is not None:
run_state.set_trace(get_current_trace())
current_turn = run_state._current_turn
raw_original_input = run_state._original_input
original_input = normalize_resumed_input(raw_original_input)
generated_items = run_state._generated_items
session_items = list(run_state._session_items)
model_responses = run_state._model_responses
# Cast to the correct type since we know this is TContext
context_wrapper = cast(RunContextWrapper[TContext], run_state._context)
else:
current_turn = 0
original_input = copy_input_items(original_input_for_state)
generated_items = []
session_items = []
model_responses = []
context_wrapper = ensure_context_wrapper(context)
set_agent_tool_state_scope(context_wrapper, None)
run_state = RunState(
context=context_wrapper,
original_input=original_input,
starting_agent=starting_agent,
max_turns=max_turns,
conversation_id=conversation_id,
previous_response_id=previous_response_id,
auto_previous_response_id=auto_previous_response_id,
)
run_state._reasoning_item_id_policy = resolved_reasoning_item_id_policy
run_state.set_trace(get_current_trace())
current_task_span: Span[TaskSpanData] = task_span(name=trace_workflow_name)
current_task_span.start(mark_as_current=True)
task_usage_start = snapshot_usage(context_wrapper.usage)
try:
sandbox_runtime = SandboxRuntime(
starting_agent=starting_agent,
run_config=run_config,
rollout_id=_sandbox_memory_rollout_id(
run_config=run_config,
conversation_id=conversation_id,
session=session,
),
run_state=run_state,
)
prompt_cache_key_resolver = PromptCacheKeyResolver.from_run_state(
run_state=run_state,
)
completed_result: RunResult | None = None
run_exception: BaseException | None = None
def _with_reasoning_item_id_policy(result: RunResult) -> RunResult:
result._reasoning_item_id_policy = resolved_reasoning_item_id_policy
if run_state is not None:
run_state._reasoning_item_id_policy = resolved_reasoning_item_id_policy
return result
def _tool_use_tracker_snapshot() -> dict[str, list[str]]:
identity_root_agent = starting_agent
if run_state is not None and run_state._starting_agent is not None:
identity_root_agent = run_state._starting_agent
return serialize_tool_use_tracker(
tool_use_tracker,
starting_agent=identity_root_agent,
)
def _finalize_result(result: RunResult) -> RunResult:
nonlocal completed_result
result._starting_agent_for_state = (
run_state._starting_agent
if run_state is not None and run_state._starting_agent is not None
else starting_agent
)
finalized_result = finalize_conversation_tracking(
_with_reasoning_item_id_policy(result),
server_conversation_tracker=server_conversation_tracker,
run_state=run_state,
)
sandbox_runtime.apply_result_metadata(finalized_result)
if run_state is not None:
finalized_result._generated_prompt_cache_key = (
run_state._generated_prompt_cache_key
)
completed_result = finalized_result
return finalized_result
pending_server_items: list[RunItem] | None = None
input_guardrail_results: list[InputGuardrailResult] = (
list(run_state._input_guardrail_results) if run_state is not None else []
)
tool_input_guardrail_results: list[ToolInputGuardrailResult] = (
list(getattr(run_state, "_tool_input_guardrail_results", []))
if run_state is not None
else []
)
tool_output_guardrail_results: list[ToolOutputGuardrailResult] = (
list(getattr(run_state, "_tool_output_guardrail_results", []))
if run_state is not None
else []
)
current_span: Span[AgentSpanData] | None = None
if (
is_resumed_state
and run_state is not None
and run_state._current_agent is not None
):
current_agent = run_state._current_agent
else:
current_agent = starting_agent
sandbox_runtime.assert_agent_supported(current_agent)
should_run_agent_start_hooks = True
store_setting = current_agent.model_settings.resolve(
run_config.model_settings
).store
if (
not is_resumed_state
and session_persistence_enabled
and original_user_input is not None
and session_input_items_for_persistence is None
):
sandbox_runtime.assert_agent_supported(current_agent)
session_input_items_for_persistence = ItemHelpers.input_to_new_input_list(
original_user_input
)
if (
session_persistence_enabled
and session_input_items_for_persistence
and not sandbox_runtime.enabled
):
# Capture the exact input saved so it can be rewound on conversation
# lock retries.
last_saved_input_snapshot_for_rewind = list(session_input_items_for_persistence)
await save_result_to_session(
session,
session_input_items_for_persistence,
[],
run_state,
store=store_setting,
)
session_input_items_for_persistence = []
except BaseException:
attach_usage_to_span(
current_task_span,
usage_delta(task_usage_start, context_wrapper.usage),
)
current_task_span.finish(reset_current=True)
raise
try:
while True:
resuming_turn = is_resumed_state
all_input_guardrails = (
starting_agent.input_guardrails + (run_config.input_guardrails or [])
if current_turn == 0 and not resuming_turn
else []
)
sequential_guardrails = [
g for g in all_input_guardrails if not g.run_in_parallel
]
parallel_guardrails = [g for g in all_input_guardrails if g.run_in_parallel]
sequential_results: list[InputGuardrailResult] = []
if sandbox_runtime.enabled and sequential_guardrails:
# Blocking first-turn guardrails must run before sandbox prep so a tripwire
# can prevent session creation, startup, or live-session mutation.
try:
sequential_results = await run_input_guardrails(
starting_agent,
sequential_guardrails,
copy_input_items(original_input),
context_wrapper,
)
except InputGuardrailTripwireTriggered:
session_input_items_for_persistence = (
await persist_session_items_for_guardrail_trip(
session,
server_conversation_tracker,
session_input_items_for_persistence,
original_user_input,
run_state,
store=store_setting,
)
)
raise
sequential_guardrails = []
current_bindings = bind_public_agent(current_agent)
execution_agent = current_bindings.execution_agent
prepared_sandbox = await sandbox_runtime.prepare_agent(
current_agent=current_agent,
current_input=original_input,
context_wrapper=context_wrapper,
is_resumed_state=resuming_turn,
)
current_bindings = prepared_sandbox.bindings
execution_agent = current_bindings.execution_agent
original_input = copy_input_items(prepared_sandbox.input)
if starting_input is not None and not isinstance(starting_input, RunState):
starting_input = copy_input_items(prepared_sandbox.input)
if run_state is not None:
run_state._original_input = copy_input_items(original_input)
normalized_starting_input: str | list[TResponseInputItem] = (
starting_input
if starting_input is not None and not isinstance(starting_input, RunState)
else ""
)
store_setting = current_agent.model_settings.resolve(
run_config.model_settings
).store
if session_persistence_enabled and session_input_items_for_persistence:
last_saved_input_snapshot_for_rewind = list(
session_input_items_for_persistence
)
await save_result_to_session(
session,
list(last_saved_input_snapshot_for_rewind),
[],
run_state,
store=store_setting,
)
session_input_items_for_persistence = []
if run_state is not None and run_state._current_step is not None:
if isinstance(run_state._current_step, NextStepInterruption):
logger.debug("Continuing from interruption")
if (
not run_state._model_responses
or not run_state._last_processed_response
):
raise UserError("No model response found in previous state")
turn_result = await resolve_interrupted_turn(
bindings=current_bindings,
original_input=original_input,
original_pre_step_items=generated_items,
new_response=run_state._model_responses[-1],
processed_response=run_state._last_processed_response,
hooks=hooks,
context_wrapper=context_wrapper,
run_config=run_config,
server_manages_conversation=server_conversation_tracker is not None,
run_state=run_state,
)
if run_state._last_processed_response is not None:
tool_use_tracker.record_processed_response(
current_agent,
run_state._last_processed_response,
)
original_input = turn_result.original_input
generated_items, turn_session_items = resumed_turn_items(turn_result)
session_items.extend(turn_session_items)
if run_state is not None:
update_run_state_after_resume(
run_state,
turn_result=turn_result,
generated_items=generated_items,
session_items=session_items,
)
if (
session_persistence_enabled
and turn_result.new_step_items
and run_state is not None
):
run_state._current_turn_persisted_item_count = (
await save_resumed_turn_items(
session=session,
items=turn_session_items,
persisted_count=(
run_state._current_turn_persisted_item_count
),
response_id=turn_result.model_response.response_id,
reasoning_item_id_policy=(
run_state._reasoning_item_id_policy
),
store=store_setting,
)
)
# After the resumed turn, treat subsequent turns as fresh so
# counters and input saving behave normally.
is_resumed_state = False
if isinstance(turn_result.next_step, NextStepInterruption):
interruption_result_input: str | list[TResponseInputItem] = (
original_input
)
append_model_response_if_new(
model_responses, turn_result.model_response
)
processed_response_for_state = resolve_processed_response(
run_state=run_state,
processed_response=turn_result.processed_response,
)
if run_state is not None:
update_run_state_for_interruption(
run_state=run_state,
model_responses=model_responses,
processed_response=processed_response_for_state,
generated_items=generated_items,
session_items=session_items,
current_turn=current_turn,
next_step=turn_result.next_step,
)
result = build_interruption_result(
result_input=interruption_result_input,
session_items=session_items,
model_responses=model_responses,
current_agent=current_agent,
input_guardrail_results=input_guardrail_results,
tool_input_guardrail_results=(
turn_result.tool_input_guardrail_results
),
tool_output_guardrail_results=(
turn_result.tool_output_guardrail_results
),
context_wrapper=context_wrapper,
interruptions=approvals_from_step(turn_result.next_step),
processed_response=processed_response_for_state,
tool_use_tracker=tool_use_tracker,
max_turns=max_turns,
current_turn=current_turn,
generated_items=generated_items,
run_state=run_state,
original_input=original_input,
)
return _finalize_result(result)
if isinstance(turn_result.next_step, NextStepRunAgain):
continue
append_model_response_if_new(
model_responses, turn_result.model_response
)
tool_input_guardrail_results.extend(
turn_result.tool_input_guardrail_results
)
tool_output_guardrail_results.extend(
turn_result.tool_output_guardrail_results
)
if isinstance(turn_result.next_step, NextStepFinalOutput):
output_guardrail_results = await run_output_guardrails(
current_agent.output_guardrails
+ (run_config.output_guardrails or []),
current_agent,
turn_result.next_step.output,
context_wrapper,
)
current_step = getattr(run_state, "_current_step", None)
approvals_from_state = approvals_from_step(current_step)
result = RunResult(
input=turn_result.original_input,
new_items=session_items,
raw_responses=model_responses,
final_output=turn_result.next_step.output,
_last_agent=current_agent,
input_guardrail_results=input_guardrail_results,
output_guardrail_results=output_guardrail_results,
tool_input_guardrail_results=tool_input_guardrail_results,
tool_output_guardrail_results=tool_output_guardrail_results,
context_wrapper=context_wrapper,
interruptions=approvals_from_state,
_tool_use_tracker_snapshot=_tool_use_tracker_snapshot(),
max_turns=max_turns,
)
result._current_turn = current_turn
result._model_input_items = list(generated_items)
# Keep normalized replay aligned with the model-facing
# continuation whenever session history preserved extra items.
result._replay_from_model_input_items = list(
generated_items
) != list(session_items)
if run_state is not None:
result._trace_state = run_state._trace_state
if session_persistence_enabled:
input_items_for_save_1: list[TResponseInputItem] = (
session_input_items_for_persistence
if session_input_items_for_persistence is not None
else []
)
await save_result_to_session(
session,
input_items_for_save_1,
session_items_for_turn(turn_result),
run_state,
response_id=turn_result.model_response.response_id,
store=store_setting,
)
result._original_input = copy_input_items(original_input)
return _finalize_result(result)
elif isinstance(turn_result.next_step, NextStepHandoff):
current_agent = cast(
Agent[TContext], turn_result.next_step.new_agent
)
if run_state is not None:
run_state._current_agent = current_agent
starting_input = turn_result.original_input
original_input = turn_result.original_input