-
Notifications
You must be signed in to change notification settings - Fork 4k
Expand file tree
/
Copy pathrun.py
More file actions
2188 lines (1933 loc) · 91.2 KB
/
run.py
File metadata and controls
2188 lines (1933 loc) · 91.2 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 inspect
import os
import warnings
from dataclasses import dataclass, field
from typing import Any, Callable, Generic, cast, get_args, get_origin
from openai.types.responses import (
ResponseCompletedEvent,
ResponseOutputItemDoneEvent,
)
from openai.types.responses.response_prompt_param import (
ResponsePromptParam,
)
from openai.types.responses.response_reasoning_item import ResponseReasoningItem
from typing_extensions import NotRequired, TypedDict, Unpack
from ._run_impl import (
AgentToolUseTracker,
NextStepFinalOutput,
NextStepHandoff,
NextStepRunAgain,
QueueCompleteSentinel,
RunImpl,
SingleStepResult,
TraceCtxManager,
get_model_tracing_impl,
)
from .agent import Agent
from .agent_output import AgentOutputSchema, AgentOutputSchemaBase
from .exceptions import (
AgentsException,
InputGuardrailTripwireTriggered,
MaxTurnsExceeded,
ModelBehaviorError,
OutputGuardrailTripwireTriggered,
RunErrorDetails,
UserError,
)
from .guardrail import (
InputGuardrail,
InputGuardrailResult,
OutputGuardrail,
OutputGuardrailResult,
)
from .handoffs import Handoff, HandoffHistoryMapper, HandoffInputFilter, handoff
from .items import (
HandoffCallItem,
HandoffOutputItem,
ItemHelpers,
ModelResponse,
ReasoningItem,
RunItem,
ToolCallItem,
ToolCallItemTypes,
ToolCallOutputItem,
TResponseInputItem,
)
from .lifecycle import AgentHooksBase, RunHooks, RunHooksBase
from .logger import logger
from .memory import (
OpenAIResponsesCompactionArgs,
Session,
SessionInputCallback,
is_openai_responses_compaction_aware_session,
)
from .model_settings import ModelSettings
from .models.interface import Model, ModelProvider
from .models.multi_provider import MultiProvider
from .result import RunResult, RunResultStreaming
from .run_context import AgentHookContext, RunContextWrapper, TContext
from .stream_events import (
AgentUpdatedStreamEvent,
RawResponsesStreamEvent,
RunItemStreamEvent,
StreamEvent,
)
from .tool import Tool, dispose_resolved_computers
from .tool_guardrails import ToolInputGuardrailResult, ToolOutputGuardrailResult
from .tracing import Span, SpanError, TracingConfig, agent_span, get_current_trace, trace
from .tracing.span_data import AgentSpanData
from .usage import Usage
from .util import _coro, _error_tracing
from .util._types import MaybeAwaitable
DEFAULT_MAX_TURNS = 10
DEFAULT_AGENT_RUNNER: AgentRunner = None # type: ignore
# the value is set at the end of the module
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 _default_trace_include_sensitive_data() -> bool:
"""Returns the default value for trace_include_sensitive_data based on environment variable."""
val = os.getenv("OPENAI_AGENTS_TRACE_INCLUDE_SENSITIVE_DATA", "true")
return val.strip().lower() in ("1", "true", "yes", "on")
@dataclass
class ModelInputData:
"""Container for the data that will be sent to the model."""
input: list[TResponseInputItem]
instructions: str | None
@dataclass
class CallModelData(Generic[TContext]):
"""Data passed to `RunConfig.call_model_input_filter` prior to model call."""
model_data: ModelInputData
agent: Agent[TContext]
context: TContext | None
@dataclass
class _ServerConversationTracker:
"""Tracks server-side conversation state for either conversation_id or
previous_response_id modes.
Note: When auto_previous_response_id=True is used, response chaining is enabled
automatically for the first turn, even when there's no actual previous response ID yet.
"""
conversation_id: str | None = None
previous_response_id: str | None = None
auto_previous_response_id: bool = False
sent_items: set[int] = field(default_factory=set)
server_items: set[int] = field(default_factory=set)
def track_server_items(self, model_response: ModelResponse) -> None:
for output_item in model_response.output:
self.server_items.add(id(output_item))
# Update previous_response_id when using previous_response_id mode or auto mode
if (
self.conversation_id is None
and (self.previous_response_id is not None or self.auto_previous_response_id)
and model_response.response_id is not None
):
self.previous_response_id = model_response.response_id
def prepare_input(
self,
original_input: str | list[TResponseInputItem],
generated_items: list[RunItem],
) -> list[TResponseInputItem]:
input_items: list[TResponseInputItem] = []
# On first call (when there are no generated items yet), include the original input
if not generated_items:
input_items.extend(ItemHelpers.input_to_new_input_list(original_input))
# Process generated_items, skip items already sent or from server
for item in generated_items:
raw_item_id = id(item.raw_item)
if raw_item_id in self.sent_items or raw_item_id in self.server_items:
continue
input_items.append(item.to_input_item())
self.sent_items.add(raw_item_id)
return input_items
# Type alias for the optional input filter callback
CallModelInputFilter = Callable[[CallModelData[Any]], MaybeAwaitable[ModelInputData]]
@dataclass
class RunConfig:
"""Configures settings for the entire agent run."""
model: str | Model | None = None
"""The model to use for the entire agent run. If set, will override the model set on every
agent. The model_provider passed in below must be able to resolve this model name.
"""
model_provider: ModelProvider = field(default_factory=MultiProvider)
"""The model provider to use when looking up string model names. Defaults to OpenAI."""
model_settings: ModelSettings | None = None
"""Configure global model settings. Any non-null values will override the agent-specific model
settings.
"""
handoff_input_filter: HandoffInputFilter | None = None
"""A global input filter to apply to all handoffs. If `Handoff.input_filter` is set, then that
will take precedence. The input filter allows you to edit the inputs that are sent to the new
agent. See the documentation in `Handoff.input_filter` for more details.
"""
nest_handoff_history: bool = False
"""Opt-in beta: wrap prior run history in a single assistant message before handing off when no
custom input filter is set. This is disabled by default while we stabilize nested handoffs; set
to True to enable the collapsed transcript behavior.
"""
handoff_history_mapper: HandoffHistoryMapper | None = None
"""Optional function that receives the normalized transcript (history + handoff items) and
returns the input history that should be passed to the next agent. When left as `None`, the
runner collapses the transcript into a single assistant message. This function only runs when
`nest_handoff_history` is True.
"""
input_guardrails: list[InputGuardrail[Any]] | None = None
"""A list of input guardrails to run on the initial run input."""
output_guardrails: list[OutputGuardrail[Any]] | None = None
"""A list of output guardrails to run on the final output of the run."""
tracing_disabled: bool = False
"""Whether tracing is disabled for the agent run. If disabled, we will not trace the agent run.
"""
tracing: TracingConfig | None = None
"""Tracing configuration for this run."""
trace_include_sensitive_data: bool = field(
default_factory=_default_trace_include_sensitive_data
)
"""Whether we include potentially sensitive data (for example: inputs/outputs of tool calls or
LLM generations) in traces. If False, we'll still create spans for these events, but the
sensitive data will not be included.
"""
workflow_name: str = "Agent workflow"
"""The name of the run, used for tracing. Should be a logical name for the run, like
"Code generation workflow" or "Customer support agent".
"""
trace_id: str | None = None
"""A custom trace ID to use for tracing. If not provided, we will generate a new trace ID."""
group_id: str | None = None
"""
A grouping identifier to use for tracing, to link multiple traces from the same conversation
or process. For example, you might use a chat thread ID.
"""
trace_metadata: dict[str, Any] | None = None
"""
An optional dictionary of additional metadata to include with the trace.
"""
session_input_callback: SessionInputCallback | None = None
"""Defines how to handle session history when new input is provided.
- `None` (default): The new input is appended to the session history.
- `SessionInputCallback`: A custom function that receives the history and new input, and
returns the desired combined list of items.
"""
call_model_input_filter: CallModelInputFilter | None = None
"""
Optional callback that is invoked immediately before calling the model. It receives the current
agent, context and the model input (instructions and input items), and must return a possibly
modified `ModelInputData` to use for the model call.
This allows you to edit the input sent to the model e.g. to stay within a token limit.
For example, you can use this to add a system prompt to the input.
"""
class RunOptions(TypedDict, Generic[TContext]):
"""Arguments for ``AgentRunner`` methods."""
context: NotRequired[TContext | None]
"""The context for the run."""
max_turns: NotRequired[int]
"""The maximum number of turns to run for."""
hooks: NotRequired[RunHooks[TContext] | None]
"""Lifecycle hooks for the run."""
run_config: NotRequired[RunConfig | None]
"""Run configuration."""
previous_response_id: NotRequired[str | None]
"""The ID of the previous response, if any."""
auto_previous_response_id: NotRequired[bool]
"""Enable automatic response chaining for the first turn."""
conversation_id: NotRequired[str | None]
"""The ID of the stored conversation, if any."""
session: NotRequired[Session | None]
"""The session for the run."""
class Runner:
@classmethod
async def run(
cls,
starting_agent: Agent[TContext],
input: str | list[TResponseInputItem],
*,
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,
) -> 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.
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.
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,
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],
*,
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,
) -> 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.
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.
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,
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],
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,
) -> 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.
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.
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,
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],
**kwargs: Unpack[RunOptions[TContext]],
) -> RunResult:
context = kwargs.get("context")
max_turns = kwargs.get("max_turns", DEFAULT_MAX_TURNS)
hooks = cast(RunHooks[TContext], self._validate_run_hooks(kwargs.get("hooks")))
run_config = kwargs.get("run_config")
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()
# 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 = _ServerConversationTracker(
conversation_id=conversation_id,
previous_response_id=previous_response_id,
auto_previous_response_id=auto_previous_response_id,
)
else:
server_conversation_tracker = None
# Keep original user input separate from session-prepared input
original_user_input = input
prepared_input = await self._prepare_input_with_session(
input, session, run_config.session_input_callback
)
tool_use_tracker = AgentToolUseTracker()
with TraceCtxManager(
workflow_name=run_config.workflow_name,
trace_id=run_config.trace_id,
group_id=run_config.group_id,
metadata=run_config.trace_metadata,
tracing=run_config.tracing,
disabled=run_config.tracing_disabled,
):
current_turn = 0
original_input: str | list[TResponseInputItem] = _copy_str_or_list(prepared_input)
generated_items: list[RunItem] = [] # For model input (may be filtered on handoffs)
session_items: list[RunItem] = [] # For observability (always unfiltered)
model_responses: list[ModelResponse] = []
context_wrapper: RunContextWrapper[TContext] = RunContextWrapper(
context=context, # type: ignore
)
input_guardrail_results: list[InputGuardrailResult] = []
tool_input_guardrail_results: list[ToolInputGuardrailResult] = []
tool_output_guardrail_results: list[ToolOutputGuardrailResult] = []
current_span: Span[AgentSpanData] | None = None
current_agent = starting_agent
should_run_agent_start_hooks = True
# save only the new user input to the session, not the combined history
await self._save_result_to_session(session, original_user_input, [])
try:
while True:
all_tools = await AgentRunner._get_all_tools(current_agent, context_wrapper)
await RunImpl.initialize_computer_tools(
tools=all_tools, context_wrapper=context_wrapper
)
# Start an agent span if we don't have one. This span is ended if the current
# agent changes, or if the agent loop ends.
if current_span is None:
handoff_names = [
h.agent_name
for h in await AgentRunner._get_handoffs(current_agent, context_wrapper)
]
if output_schema := AgentRunner._get_output_schema(current_agent):
output_type_name = output_schema.name()
else:
output_type_name = "str"
current_span = agent_span(
name=current_agent.name,
handoffs=handoff_names,
output_type=output_type_name,
)
current_span.start(mark_as_current=True)
current_span.span_data.tools = [t.name for t in all_tools]
current_turn += 1
if current_turn > max_turns:
_error_tracing.attach_error_to_span(
current_span,
SpanError(
message="Max turns exceeded",
data={"max_turns": max_turns},
),
)
raise MaxTurnsExceeded(f"Max turns ({max_turns}) exceeded")
logger.debug(
f"Running agent {current_agent.name} (turn {current_turn})",
)
if current_turn == 1:
# Separate guardrails based on execution mode.
all_input_guardrails = starting_agent.input_guardrails + (
run_config.input_guardrails or []
)
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]
# Run blocking guardrails first, before agent starts.
# (will raise exception if tripwire triggered).
sequential_results = []
if sequential_guardrails:
sequential_results = await self._run_input_guardrails(
starting_agent,
sequential_guardrails,
_copy_str_or_list(prepared_input),
context_wrapper,
)
# Run parallel guardrails + agent together.
input_guardrail_results, turn_result = await asyncio.gather(
self._run_input_guardrails(
starting_agent,
parallel_guardrails,
_copy_str_or_list(prepared_input),
context_wrapper,
),
self._run_single_turn(
agent=current_agent,
all_tools=all_tools,
original_input=original_input,
generated_items=generated_items,
hooks=hooks,
context_wrapper=context_wrapper,
run_config=run_config,
should_run_agent_start_hooks=should_run_agent_start_hooks,
tool_use_tracker=tool_use_tracker,
server_conversation_tracker=server_conversation_tracker,
),
)
# Combine sequential and parallel results.
input_guardrail_results = sequential_results + input_guardrail_results
else:
turn_result = await self._run_single_turn(
agent=current_agent,
all_tools=all_tools,
original_input=original_input,
generated_items=generated_items,
hooks=hooks,
context_wrapper=context_wrapper,
run_config=run_config,
should_run_agent_start_hooks=should_run_agent_start_hooks,
tool_use_tracker=tool_use_tracker,
server_conversation_tracker=server_conversation_tracker,
)
should_run_agent_start_hooks = False
model_responses.append(turn_result.model_response)
original_input = turn_result.original_input
# For model input, use new_step_items (filtered on handoffs)
generated_items = turn_result.pre_step_items + turn_result.new_step_items
# Accumulate unfiltered items for observability
session_items_for_turn = (
turn_result.session_step_items
if turn_result.session_step_items is not None
else turn_result.new_step_items
)
session_items.extend(session_items_for_turn)
store_setting = current_agent.model_settings.resolve(
run_config.model_settings
).store
if server_conversation_tracker is not None:
server_conversation_tracker.track_server_items(turn_result.model_response)
# Collect tool guardrail results from this turn
tool_input_guardrail_results.extend(turn_result.tool_input_guardrail_results)
tool_output_guardrail_results.extend(turn_result.tool_output_guardrail_results)
try:
if isinstance(turn_result.next_step, NextStepFinalOutput):
output_guardrail_results = await self._run_output_guardrails(
current_agent.output_guardrails
+ (run_config.output_guardrails or []),
current_agent,
turn_result.next_step.output,
context_wrapper,
)
result = RunResult(
input=original_input,
new_items=session_items, # Use unfiltered items for observability
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,
)
if not any(
guardrail_result.output.tripwire_triggered
for guardrail_result in input_guardrail_results
):
await self._save_result_to_session(
session,
[],
turn_result.session_step_items
if turn_result.session_step_items is not None
else turn_result.new_step_items,
turn_result.model_response.response_id,
store=store_setting,
)
return result
elif isinstance(turn_result.next_step, NextStepHandoff):
# Save the conversation to session if enabled (before handoff)
if session is not None:
if not any(
guardrail_result.output.tripwire_triggered
for guardrail_result in input_guardrail_results
):
await self._save_result_to_session(
session,
[],
turn_result.session_step_items
if turn_result.session_step_items is not None
else turn_result.new_step_items,
turn_result.model_response.response_id,
store=store_setting,
)
current_agent = cast(Agent[TContext], turn_result.next_step.new_agent)
current_span.finish(reset_current=True)
current_span = None
should_run_agent_start_hooks = True
elif isinstance(turn_result.next_step, NextStepRunAgain):
if not any(
guardrail_result.output.tripwire_triggered
for guardrail_result in input_guardrail_results
):
await self._save_result_to_session(
session,
[],
turn_result.session_step_items
if turn_result.session_step_items is not None
else turn_result.new_step_items,
turn_result.model_response.response_id,
store=store_setting,
)
else:
raise AgentsException(
f"Unknown next step type: {type(turn_result.next_step)}"
)
finally:
# RunImpl.execute_tools_and_side_effects returns a SingleStepResult that
# stores direct references to the `pre_step_items` and `new_step_items`
# lists it manages internally. Clear them here so the next turn does not
# hold on to items from previous turns and to avoid leaking agent refs.
turn_result.pre_step_items.clear()
turn_result.new_step_items.clear()
except AgentsException as exc:
exc.run_data = RunErrorDetails(
input=original_input,
new_items=session_items, # Use unfiltered items for observability
raw_responses=model_responses,
last_agent=current_agent,
context_wrapper=context_wrapper,
input_guardrail_results=input_guardrail_results,
output_guardrail_results=[],
)
raise
finally:
try:
await dispose_resolved_computers(run_context=context_wrapper)
except Exception as error:
logger.warning("Failed to dispose computers after run: %s", error)
if current_span:
current_span.finish(reset_current=True)
def run_sync(
self,
starting_agent: Agent[TContext],
input: str | list[TResponseInputItem],
**kwargs: Unpack[RunOptions[TContext]],
) -> RunResult:
context = kwargs.get("context")
max_turns = kwargs.get("max_turns", DEFAULT_MAX_TURNS)
hooks = kwargs.get("hooks")
run_config = kwargs.get("run_config")
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")
# Python 3.14 stopped implicitly wiring up a default event loop
# when synchronous code touches asyncio APIs for the first time.
# Several of our synchronous entry points (for example the Redis/SQLAlchemy session helpers)
# construct asyncio primitives like asyncio.Lock during __init__,
# which binds them to whatever loop happens to be the thread's default at that moment.
# To keep those locks usable we must ensure that run_sync reuses that same default loop
# instead of hopping over to a brand-new asyncio.run() loop.
try:
already_running_loop = asyncio.get_running_loop()
except RuntimeError:
already_running_loop = None
if already_running_loop is not None:
# This method is only expected to run when no loop is already active.
# (Each thread has its own default loop; concurrent sync runs should happen on
# different threads. In a single thread use the async API to interleave work.)
raise RuntimeError(
"AgentRunner.run_sync() cannot be called when an event loop is already running."
)
policy = asyncio.get_event_loop_policy()
with warnings.catch_warnings():
warnings.simplefilter("ignore", DeprecationWarning)
try:
default_loop = policy.get_event_loop()
except RuntimeError:
default_loop = policy.new_event_loop()
policy.set_event_loop(default_loop)
# We intentionally leave the default loop open even if we had to create one above. Session
# instances and other helpers stash loop-bound primitives between calls and expect to find
# the same default loop every time run_sync is invoked on this thread.
# Schedule the async run on the default loop so that we can manage cancellation explicitly.
task = default_loop.create_task(
self.run(
starting_agent,
input,
session=session,
context=context,
max_turns=max_turns,
hooks=hooks,
run_config=run_config,
previous_response_id=previous_response_id,
auto_previous_response_id=auto_previous_response_id,
conversation_id=conversation_id,
)
)
try:
# Drive the coroutine to completion, harvesting the final RunResult.
return default_loop.run_until_complete(task)
except BaseException:
# If the sync caller aborts (KeyboardInterrupt, etc.), make sure the scheduled task
# does not linger on the shared loop by cancelling it and waiting for completion.
if not task.done():
task.cancel()
with contextlib.suppress(asyncio.CancelledError):
default_loop.run_until_complete(task)
raise
finally:
if not default_loop.is_closed():
# The loop stays open for subsequent runs, but we still need to flush any pending
# async generators so their cleanup code executes promptly.
with contextlib.suppress(RuntimeError):
default_loop.run_until_complete(default_loop.shutdown_asyncgens())
def run_streamed(
self,
starting_agent: Agent[TContext],
input: str | list[TResponseInputItem],
**kwargs: Unpack[RunOptions[TContext]],
) -> RunResultStreaming:
context = kwargs.get("context")
max_turns = kwargs.get("max_turns", DEFAULT_MAX_TURNS)
hooks = cast(RunHooks[TContext], self._validate_run_hooks(kwargs.get("hooks")))
run_config = kwargs.get("run_config")
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()
# If there's already a trace, we don't create a new one. In addition, we can't end the
# trace here, because the actual work is done in `stream_events` and this method ends
# before that.
new_trace = (
None
if get_current_trace()
else trace(
workflow_name=run_config.workflow_name,
trace_id=run_config.trace_id,
group_id=run_config.group_id,
metadata=run_config.trace_metadata,
tracing=run_config.tracing,
disabled=run_config.tracing_disabled,
)
)
output_schema = AgentRunner._get_output_schema(starting_agent)
context_wrapper: RunContextWrapper[TContext] = RunContextWrapper(
context=context # type: ignore
)
streamed_result = RunResultStreaming(
input=_copy_str_or_list(input),
new_items=[],
current_agent=starting_agent,
raw_responses=[],
final_output=None,
is_complete=False,
current_turn=0,
max_turns=max_turns,
input_guardrail_results=[],
output_guardrail_results=[],
tool_input_guardrail_results=[],
tool_output_guardrail_results=[],
_current_agent_output_schema=output_schema,
trace=new_trace,
context_wrapper=context_wrapper,
)
# Kick off the actual agent loop in the background and return the streamed result object.
streamed_result._run_impl_task = asyncio.create_task(
self._start_streaming(
starting_input=input,
streamed_result=streamed_result,
starting_agent=starting_agent,
max_turns=max_turns,
hooks=hooks,
context_wrapper=context_wrapper,
run_config=run_config,
previous_response_id=previous_response_id,
auto_previous_response_id=auto_previous_response_id,
conversation_id=conversation_id,
session=session,
)
)
return streamed_result
@staticmethod
def _validate_run_hooks(
hooks: RunHooksBase[Any, Agent[Any]] | AgentHooksBase[Any, Agent[Any]] | Any | None,
) -> RunHooks[Any]:
if hooks is None:
return RunHooks[Any]()
input_hook_type = type(hooks).__name__
if isinstance(hooks, AgentHooksBase):
raise TypeError(