-
Notifications
You must be signed in to change notification settings - Fork 3.7k
Expand file tree
/
Copy pathtool.py
More file actions
1921 lines (1509 loc) · 70.8 KB
/
tool.py
File metadata and controls
1921 lines (1509 loc) · 70.8 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 ast
import asyncio
import copy
import dataclasses
import inspect
import json
import math
import weakref
from collections.abc import Awaitable, Mapping
from dataclasses import dataclass, field
from types import UnionType
from typing import (
TYPE_CHECKING,
Annotated,
Any,
Callable,
Generic,
Literal,
Protocol,
TypeVar,
Union,
cast,
get_args,
get_origin,
get_type_hints,
overload,
)
from openai.types.responses.file_search_tool_param import Filters, RankingOptions
from openai.types.responses.response_computer_tool_call import (
PendingSafetyCheck,
ResponseComputerToolCall,
)
from openai.types.responses.response_output_item import LocalShellCall, McpApprovalRequest
from openai.types.responses.tool_param import CodeInterpreter, ImageGeneration, Mcp
from openai.types.responses.web_search_tool import Filters as WebSearchToolFilters
from openai.types.responses.web_search_tool_param import UserLocation
from pydantic import BaseModel, TypeAdapter, ValidationError, model_validator
from typing_extensions import Concatenate, NotRequired, ParamSpec, TypedDict
from . import _debug
from ._tool_identity import (
get_explicit_function_tool_namespace,
tool_qualified_name,
validate_function_tool_lookup_configuration,
validate_function_tool_namespace_shape,
)
from .computer import AsyncComputer, Computer
from .editor import ApplyPatchEditor, ApplyPatchOperation
from .exceptions import ModelBehaviorError, ToolTimeoutError, UserError
from .function_schema import DocstringStyle, function_schema
from .logger import logger
from .run_context import RunContextWrapper
from .strict_schema import ensure_strict_json_schema
from .tool_context import ToolContext
from .tool_guardrails import ToolInputGuardrail, ToolOutputGuardrail
from .tracing import SpanError
from .util import _error_tracing
from .util._types import MaybeAwaitable
if TYPE_CHECKING:
from .agent import Agent, AgentBase
from .items import RunItem, ToolApprovalItem
ToolParams = ParamSpec("ToolParams")
ToolFunctionWithoutContext = Callable[ToolParams, Any]
ToolFunctionWithContext = Callable[Concatenate[RunContextWrapper[Any], ToolParams], Any]
ToolFunctionWithToolContext = Callable[Concatenate[ToolContext, ToolParams], Any]
ToolFunction = Union[
ToolFunctionWithoutContext[ToolParams],
ToolFunctionWithContext[ToolParams],
ToolFunctionWithToolContext[ToolParams],
]
DEFAULT_APPROVAL_REJECTION_MESSAGE = "Tool execution was not approved."
ToolTimeoutBehavior = Literal["error_as_result", "raise_exception"]
ToolErrorFunction = Callable[[RunContextWrapper[Any], Exception], MaybeAwaitable[str]]
_SYNC_FUNCTION_TOOL_MARKER = "__agents_sync_function_tool__"
_UNSET_FAILURE_ERROR_FUNCTION = object()
class ToolOutputText(BaseModel):
"""Represents a tool output that should be sent to the model as text."""
type: Literal["text"] = "text"
text: str
class ToolOutputTextDict(TypedDict, total=False):
"""TypedDict variant for text tool outputs."""
type: Literal["text"]
text: str
class ToolOutputImage(BaseModel):
"""Represents a tool output that should be sent to the model as an image.
You can provide either an `image_url` (URL or data URL) or a `file_id` for previously uploaded
content. The optional `detail` can control vision detail.
"""
type: Literal["image"] = "image"
image_url: str | None = None
file_id: str | None = None
detail: Literal["low", "high", "auto"] | None = None
@model_validator(mode="after")
def check_at_least_one_required_field(self) -> ToolOutputImage:
"""Validate that at least one of image_url or file_id is provided."""
if self.image_url is None and self.file_id is None:
raise ValueError("At least one of image_url or file_id must be provided")
return self
class ToolOutputImageDict(TypedDict, total=False):
"""TypedDict variant for image tool outputs."""
type: Literal["image"]
image_url: NotRequired[str]
file_id: NotRequired[str]
detail: NotRequired[Literal["low", "high", "auto"]]
class ToolOutputFileContent(BaseModel):
"""Represents a tool output that should be sent to the model as a file.
Provide one of `file_data` (base64), `file_url`, or `file_id`. You may also
provide an optional `filename` when using `file_data` to hint file name.
"""
type: Literal["file"] = "file"
file_data: str | None = None
file_url: str | None = None
file_id: str | None = None
filename: str | None = None
@model_validator(mode="after")
def check_at_least_one_required_field(self) -> ToolOutputFileContent:
"""Validate that at least one of file_data, file_url, or file_id is provided."""
if self.file_data is None and self.file_url is None and self.file_id is None:
raise ValueError("At least one of file_data, file_url, or file_id must be provided")
return self
class ToolOutputFileContentDict(TypedDict, total=False):
"""TypedDict variant for file content tool outputs."""
type: Literal["file"]
file_data: NotRequired[str]
file_url: NotRequired[str]
file_id: NotRequired[str]
filename: NotRequired[str]
ValidToolOutputPydanticModels = Union[ToolOutputText, ToolOutputImage, ToolOutputFileContent]
ValidToolOutputPydanticModelsTypeAdapter: TypeAdapter[ValidToolOutputPydanticModels] = TypeAdapter(
ValidToolOutputPydanticModels
)
ComputerLike = Union[Computer, AsyncComputer]
ComputerT = TypeVar("ComputerT", bound=ComputerLike)
ComputerT_co = TypeVar("ComputerT_co", bound=ComputerLike, covariant=True)
ComputerT_contra = TypeVar("ComputerT_contra", bound=ComputerLike, contravariant=True)
class ComputerCreate(Protocol[ComputerT_co]):
"""Initializes a computer for the current run context."""
def __call__(self, *, run_context: RunContextWrapper[Any]) -> MaybeAwaitable[ComputerT_co]: ...
class ComputerDispose(Protocol[ComputerT_contra]):
"""Cleans up a computer initialized for a run context."""
def __call__(
self,
*,
run_context: RunContextWrapper[Any],
computer: ComputerT_contra,
) -> MaybeAwaitable[None]: ...
@dataclass
class ComputerProvider(Generic[ComputerT]):
"""Configures create/dispose hooks for per-run computer lifecycle management."""
create: ComputerCreate[ComputerT]
dispose: ComputerDispose[ComputerT] | None = None
ComputerConfig = Union[
ComputerT,
ComputerCreate[ComputerT],
ComputerProvider[ComputerT],
]
@dataclass
class FunctionToolResult:
tool: FunctionTool
"""The tool that was run."""
output: Any
"""The output of the tool."""
run_item: RunItem | None
"""The run item that was produced as a result of the tool call.
This can be None when the tool run is interrupted and no output item should be emitted yet.
"""
interruptions: list[ToolApprovalItem] = field(default_factory=list)
"""Interruptions from nested agent runs (for agent-as-tool)."""
agent_run_result: Any = None # RunResult | None, but avoid circular import
"""Nested agent run result (for agent-as-tool)."""
@dataclass
class FunctionTool:
"""A tool that wraps a function. In most cases, you should use the `function_tool` helpers to
create a FunctionTool, as they let you easily wrap a Python function.
"""
name: str
"""The name of the tool, as shown to the LLM. Generally the name of the function."""
description: str
"""A description of the tool, as shown to the LLM."""
params_json_schema: dict[str, Any]
"""The JSON schema for the tool's parameters."""
on_invoke_tool: Callable[[ToolContext[Any], str], Awaitable[Any]]
"""A function that invokes the tool with the given context and parameters. The params passed
are:
1. The tool run context.
2. The arguments from the LLM, as a JSON string.
You must return a one of the structured tool output types (e.g. ToolOutputText, ToolOutputImage,
ToolOutputFileContent) or a string representation of the tool output, or a list of them,
or something we can call `str()` on.
In case of errors, you can either raise an Exception (which will cause the run to fail) or
return a string error message (which will be sent back to the LLM).
"""
strict_json_schema: bool = True
"""Whether the JSON schema is in strict mode. We **strongly** recommend setting this to True,
as it increases the likelihood of correct JSON input."""
is_enabled: bool | Callable[[RunContextWrapper[Any], AgentBase], MaybeAwaitable[bool]] = True
"""Whether the tool is enabled. Either a bool or a Callable that takes the run context and agent
and returns whether the tool is enabled. You can use this to dynamically enable/disable a tool
based on your context/state."""
# Keep guardrail fields before needs_approval to preserve v0.7.0 positional
# constructor compatibility for public FunctionTool callers.
# Tool-specific guardrails.
tool_input_guardrails: list[ToolInputGuardrail[Any]] | None = None
"""Optional list of input guardrails to run before invoking this tool."""
tool_output_guardrails: list[ToolOutputGuardrail[Any]] | None = None
"""Optional list of output guardrails to run after invoking this tool."""
needs_approval: (
bool | Callable[[RunContextWrapper[Any], dict[str, Any], str], Awaitable[bool]]
) = False
"""Whether the tool needs approval before execution. If True, the run will be interrupted
and the tool call will need to be approved using RunState.approve() or rejected using
RunState.reject() before continuing. Can be a bool (always/never needs approval) or a
function that takes (run_context, tool_parameters, call_id) and returns whether this
specific call needs approval."""
# Keep timeout fields after needs_approval to preserve positional constructor compatibility.
timeout_seconds: float | None = None
"""Optional timeout (seconds) for each tool invocation."""
timeout_behavior: ToolTimeoutBehavior = "error_as_result"
"""How to handle timeout events.
- "error_as_result": return a model-visible timeout error string.
- "raise_exception": raise a ToolTimeoutError and fail the run.
"""
timeout_error_function: ToolErrorFunction | None = None
"""Optional formatter for timeout errors when timeout_behavior is "error_as_result"."""
defer_loading: bool = False
"""Whether the Responses API should hide this tool definition until tool search loads it."""
_failure_error_function: ToolErrorFunction | None = field(
default=None,
kw_only=True,
repr=False,
)
"""Internal error formatter metadata used for synthetic tool-failure outputs."""
_use_default_failure_error_function: bool = field(
default=True,
kw_only=True,
repr=False,
)
"""Whether runtime-generated tool failures should use the default formatter."""
_is_agent_tool: bool = field(default=False, kw_only=True, repr=False)
"""Internal flag indicating if this tool is an agent-as-tool."""
_is_codex_tool: bool = field(default=False, kw_only=True, repr=False)
"""Internal flag indicating if this tool is a Codex tool wrapper."""
_agent_instance: Any = field(default=None, kw_only=True, repr=False)
"""Internal reference to the agent instance if this is an agent-as-tool."""
_tool_namespace: str | None = field(default=None, kw_only=True, repr=False)
"""Internal namespace metadata used to group function tools for the Responses API."""
_tool_namespace_description: str | None = field(default=None, kw_only=True, repr=False)
"""Internal namespace description used when serializing grouped function tools."""
_mcp_title: str | None = field(default=None, kw_only=True, repr=False)
"""Internal MCP display title used for ToolCallItem metadata."""
@property
def qualified_name(self) -> str:
"""Return the public qualified name used to identify this function tool."""
return (
tool_qualified_name(self.name, get_explicit_function_tool_namespace(self)) or self.name
)
def __post_init__(self):
bind_to_function_tool = getattr(self.on_invoke_tool, "__agents_bind_function_tool__", None)
if callable(bind_to_function_tool):
self.on_invoke_tool = bind_to_function_tool(self)
if self.strict_json_schema:
self.params_json_schema = ensure_strict_json_schema(self.params_json_schema)
_validate_function_tool_timeout_config(self)
def __copy__(self) -> FunctionTool:
copied_tool = dataclasses.replace(self)
dataclass_field_names = {tool_field.name for tool_field in dataclasses.fields(FunctionTool)}
for tool_field in dataclasses.fields(FunctionTool):
if tool_field.init:
continue
setattr(copied_tool, tool_field.name, getattr(self, tool_field.name))
for attr_name, attr_value in self.__dict__.items():
if attr_name not in dataclass_field_names:
setattr(copied_tool, attr_name, attr_value)
return copied_tool
def __get__(self, obj: Any, objtype: Any = None) -> FunctionTool:
"""Descriptor protocol: bind this method tool to a class instance.
When a :func:`function_tool`-decorated method is accessed on an instance
(e.g. ``my_instance.my_tool``), this returns a new :class:`FunctionTool`
whose invocation automatically prepends ``my_instance`` as the receiver,
so the underlying method receives the correct ``self``/``cls`` argument.
Accessing the tool on the *class* (``MyClass.my_tool``) returns the
unbound :class:`FunctionTool` unchanged.
"""
if obj is None:
# Class-level access — return the unbound tool descriptor.
return self
make_impl = getattr(self, "_make_impl", None)
if make_impl is None:
# Not a method tool; behave as a plain attribute (no binding needed).
return self
# Build a copy and rewire its invoker to use the bound receiver.
bound_tool = copy.copy(self)
handler = bound_tool.on_invoke_tool
if isinstance(handler, _FailureHandlingFunctionToolInvoker):
handler._invoke_tool_impl = make_impl(obj)
return bound_tool
class _FailureHandlingFunctionToolInvoker:
"""Internal callable that rebinds wrapper error handling for copied FunctionTools."""
def __init__(
self,
invoke_tool_impl: Callable[[ToolContext[Any], str], Awaitable[Any]],
on_handled_error: Callable[[FunctionTool, Exception, str], None],
*,
function_tool: FunctionTool | None = None,
) -> None:
self._invoke_tool_impl = invoke_tool_impl
self._on_handled_error = on_handled_error
self._function_tool = function_tool
def __agents_bind_function_tool__(
self, function_tool: FunctionTool
) -> _FailureHandlingFunctionToolInvoker:
if self._function_tool is function_tool:
return self
bound_invoker = _FailureHandlingFunctionToolInvoker(
self._invoke_tool_impl,
self._on_handled_error,
function_tool=function_tool,
)
if getattr(self, _SYNC_FUNCTION_TOOL_MARKER, False):
setattr(bound_invoker, _SYNC_FUNCTION_TOOL_MARKER, True)
return bound_invoker
async def __call__(self, ctx: ToolContext[Any], input: str) -> Any:
try:
return await self._invoke_tool_impl(ctx, input)
except Exception as e:
assert self._function_tool is not None
result = await maybe_invoke_function_tool_failure_error_function(
function_tool=self._function_tool,
context=ctx,
error=e,
)
if result is None:
raise
self._on_handled_error(self._function_tool, e, input)
return result
def with_function_tool_failure_error_handler(
invoke_tool_impl: Callable[[ToolContext[Any], str], Awaitable[Any]],
on_handled_error: Callable[[FunctionTool, Exception, str], None],
) -> Callable[[ToolContext[Any], str], Awaitable[Any]]:
"""Wrap a tool invoker so copied FunctionTools resolve failure policy against themselves."""
return _FailureHandlingFunctionToolInvoker(invoke_tool_impl, on_handled_error)
def _build_wrapped_function_tool(
*,
name: str,
description: str,
params_json_schema: dict[str, Any],
invoke_tool_impl: Callable[[ToolContext[Any], str], Awaitable[Any]],
on_handled_error: Callable[[FunctionTool, Exception, str], None],
failure_error_function: ToolErrorFunction | None | object = _UNSET_FAILURE_ERROR_FUNCTION,
strict_json_schema: bool = True,
is_enabled: bool | Callable[[RunContextWrapper[Any], AgentBase], MaybeAwaitable[bool]] = True,
tool_input_guardrails: list[ToolInputGuardrail[Any]] | None = None,
tool_output_guardrails: list[ToolOutputGuardrail[Any]] | None = None,
needs_approval: (
bool | Callable[[RunContextWrapper[Any], dict[str, Any], str], Awaitable[bool]]
) = False,
timeout_seconds: float | None = None,
timeout_behavior: ToolTimeoutBehavior = "error_as_result",
timeout_error_function: ToolErrorFunction | None = None,
defer_loading: bool = False,
sync_invoker: bool = False,
mcp_title: str | None = None,
) -> FunctionTool:
"""Create a FunctionTool with copied-tool-aware failure handling bound in one place."""
on_invoke_tool = with_function_tool_failure_error_handler(
invoke_tool_impl,
on_handled_error,
)
if sync_invoker:
setattr(on_invoke_tool, _SYNC_FUNCTION_TOOL_MARKER, True)
return set_function_tool_failure_error_function(
FunctionTool(
name=name,
description=description,
params_json_schema=params_json_schema,
on_invoke_tool=on_invoke_tool,
strict_json_schema=strict_json_schema,
is_enabled=is_enabled,
tool_input_guardrails=tool_input_guardrails,
tool_output_guardrails=tool_output_guardrails,
needs_approval=needs_approval,
timeout_seconds=timeout_seconds,
timeout_behavior=timeout_behavior,
timeout_error_function=timeout_error_function,
defer_loading=defer_loading,
_mcp_title=mcp_title,
),
failure_error_function,
)
@dataclass
class FileSearchTool:
"""A hosted tool that lets the LLM search through a vector store. Currently only supported with
OpenAI models, using the Responses API.
"""
vector_store_ids: list[str]
"""The IDs of the vector stores to search."""
max_num_results: int | None = None
"""The maximum number of results to return."""
include_search_results: bool = False
"""Whether to include the search results in the output produced by the LLM."""
ranking_options: RankingOptions | None = None
"""Ranking options for search."""
filters: Filters | None = None
"""A filter to apply based on file attributes."""
@property
def name(self):
return "file_search"
@dataclass
class WebSearchTool:
"""A hosted tool that lets the LLM search the web. Currently only supported with OpenAI models,
using the Responses API.
"""
user_location: UserLocation | None = None
"""Optional location for the search. Lets you customize results to be relevant to a location."""
filters: WebSearchToolFilters | None = None
"""A filter to apply based on file attributes."""
search_context_size: Literal["low", "medium", "high"] = "medium"
"""The amount of context to use for the search."""
external_web_access: bool | None = None
"""Whether the web search tool may fetch live internet content.
When omitted, the API default is used. Set to `False` to request cached or
indexed-only behavior where supported.
"""
@property
def name(self):
return "web_search"
@dataclass(eq=False)
class ComputerTool(Generic[ComputerT]):
"""A local computer harness exposed through the Responses API computer tool."""
computer: ComputerConfig[ComputerT]
"""The computer implementation, or a factory that produces a computer per run."""
on_safety_check: Callable[[ComputerToolSafetyCheckData], MaybeAwaitable[bool]] | None = None
"""Optional callback to acknowledge computer tool safety checks."""
def __post_init__(self) -> None:
_store_computer_initializer(self)
@property
def name(self):
# Keep the released preview-era runtime name for hooks and persisted
# RunState compatibility. The Responses serializer selects the actual
# wire tool type separately.
return "computer_use_preview"
@property
def trace_name(self):
# Tracing should display the GA tool alias even while runtime names preserve compatibility.
return "computer"
@dataclass
class _ResolvedComputer:
computer: ComputerLike
dispose: ComputerDispose[ComputerLike] | None = None
_computer_cache: weakref.WeakKeyDictionary[
ComputerTool[Any],
weakref.WeakKeyDictionary[RunContextWrapper[Any], _ResolvedComputer],
] = weakref.WeakKeyDictionary()
_computer_initializer_map: weakref.WeakKeyDictionary[ComputerTool[Any], ComputerConfig[Any]] = (
weakref.WeakKeyDictionary()
)
_computers_by_run_context: weakref.WeakKeyDictionary[
RunContextWrapper[Any], dict[ComputerTool[Any], _ResolvedComputer]
] = weakref.WeakKeyDictionary()
async def resolve_computer(
*, tool: ComputerTool[Any], run_context: RunContextWrapper[Any]
) -> ComputerLike:
"""Resolve a computer for a given run context, initializing it if needed."""
per_context = _computer_cache.get(tool)
if per_context is None:
per_context = weakref.WeakKeyDictionary()
_computer_cache[tool] = per_context
cached = per_context.get(run_context)
if cached is not None:
_track_resolved_computer(tool=tool, run_context=run_context, resolved=cached)
return cached.computer
initializer_config = _get_computer_initializer(tool)
lifecycle: ComputerProvider[Any] | None = (
cast(ComputerProvider[Any], initializer_config)
if _is_computer_provider(initializer_config)
else None
)
initializer: ComputerCreate[Any] | None = None
disposer: ComputerDispose[Any] | None = lifecycle.dispose if lifecycle else None
if lifecycle is not None:
initializer = lifecycle.create
elif callable(initializer_config):
initializer = initializer_config
elif _is_computer_provider(tool.computer):
lifecycle_provider = cast(ComputerProvider[Any], tool.computer)
initializer = lifecycle_provider.create
disposer = lifecycle_provider.dispose
if initializer:
computer_candidate = initializer(run_context=run_context)
computer = (
await computer_candidate
if inspect.isawaitable(computer_candidate)
else computer_candidate
)
else:
computer = cast(ComputerLike, tool.computer)
if not isinstance(computer, (Computer, AsyncComputer)):
raise UserError("The computer tool did not provide a computer instance.")
resolved = _ResolvedComputer(computer=computer, dispose=disposer)
per_context[run_context] = resolved
_track_resolved_computer(tool=tool, run_context=run_context, resolved=resolved)
tool.computer = computer
return computer
async def dispose_resolved_computers(*, run_context: RunContextWrapper[Any]) -> None:
"""Dispose any computer instances created for the provided run context."""
resolved_by_tool = _computers_by_run_context.pop(run_context, None)
if not resolved_by_tool:
return
disposers: list[tuple[ComputerDispose[ComputerLike], ComputerLike]] = []
for tool, _resolved in resolved_by_tool.items():
per_context = _computer_cache.get(tool)
if per_context is not None:
per_context.pop(run_context, None)
initializer = _get_computer_initializer(tool)
if initializer is not None:
tool.computer = initializer
if _resolved.dispose is not None:
disposers.append((_resolved.dispose, _resolved.computer))
for dispose, computer in disposers:
try:
result = dispose(run_context=run_context, computer=computer)
if inspect.isawaitable(result):
await result
except Exception as exc:
logger.warning("Failed to dispose computer for run context: %s", exc)
@dataclass
class ComputerToolSafetyCheckData:
"""Information about a computer tool safety check."""
ctx_wrapper: RunContextWrapper[Any]
"""The run context."""
agent: Agent[Any]
"""The agent performing the computer action."""
tool_call: ResponseComputerToolCall
"""The computer tool call."""
safety_check: PendingSafetyCheck
"""The pending safety check to acknowledge."""
@dataclass
class MCPToolApprovalRequest:
"""A request to approve a tool call."""
ctx_wrapper: RunContextWrapper[Any]
"""The run context."""
data: McpApprovalRequest
"""The data from the MCP tool approval request."""
class MCPToolApprovalFunctionResult(TypedDict):
"""The result of an MCP tool approval function."""
approve: bool
"""Whether to approve the tool call."""
reason: NotRequired[str]
"""An optional reason, if rejected."""
MCPToolApprovalFunction = Callable[
[MCPToolApprovalRequest], MaybeAwaitable[MCPToolApprovalFunctionResult]
]
"""A function that approves or rejects a tool call."""
ShellApprovalFunction = Callable[
[RunContextWrapper[Any], "ShellActionRequest", str], MaybeAwaitable[bool]
]
"""A function that determines whether a shell action requires approval.
Takes (run_context, action, call_id) and returns whether approval is needed.
"""
class ShellOnApprovalFunctionResult(TypedDict):
"""The result of a shell tool on_approval callback."""
approve: bool
"""Whether to approve the tool call."""
reason: NotRequired[str]
"""An optional reason, if rejected."""
ShellOnApprovalFunction = Callable[
[RunContextWrapper[Any], "ToolApprovalItem"], MaybeAwaitable[ShellOnApprovalFunctionResult]
]
"""A function that auto-approves or rejects a shell tool call when approval is needed.
Takes (run_context, approval_item) and returns approval decision.
"""
ApplyPatchApprovalFunction = Callable[
[RunContextWrapper[Any], ApplyPatchOperation, str], MaybeAwaitable[bool]
]
"""A function that determines whether an apply_patch operation requires approval.
Takes (run_context, operation, call_id) and returns whether approval is needed.
"""
class ApplyPatchOnApprovalFunctionResult(TypedDict):
"""The result of an apply_patch tool on_approval callback."""
approve: bool
"""Whether to approve the tool call."""
reason: NotRequired[str]
"""An optional reason, if rejected."""
ApplyPatchOnApprovalFunction = Callable[
[RunContextWrapper[Any], "ToolApprovalItem"], MaybeAwaitable[ApplyPatchOnApprovalFunctionResult]
]
"""A function that auto-approves or rejects an apply_patch tool call when approval is needed.
Takes (run_context, approval_item) and returns approval decision.
"""
@dataclass
class HostedMCPTool:
"""A tool that allows the LLM to use a remote MCP server. The LLM will automatically list and
call tools, without requiring a round trip back to your code.
If you want to run MCP servers locally via stdio, in a VPC or other non-publicly-accessible
environment, or you just prefer to run tool calls locally, then you can instead use the servers
in `agents.mcp` and pass `Agent(mcp_servers=[...])` to the agent."""
tool_config: Mcp
"""The MCP tool config, which includes the server URL and other settings."""
on_approval_request: MCPToolApprovalFunction | None = None
"""An optional function that will be called if approval is requested for an MCP tool. If not
provided, you will need to manually add approvals/rejections to the input and call
`Runner.run(...)` again."""
@property
def name(self):
return "hosted_mcp"
@dataclass
class CodeInterpreterTool:
"""A tool that allows the LLM to execute code in a sandboxed environment."""
tool_config: CodeInterpreter
"""The tool config, which includes the container and other settings."""
@property
def name(self):
return "code_interpreter"
@dataclass
class ImageGenerationTool:
"""A tool that allows the LLM to generate images."""
tool_config: ImageGeneration
"""The tool config, which image generation settings."""
@property
def name(self):
return "image_generation"
@dataclass
class LocalShellCommandRequest:
"""A request to execute a command on a shell."""
ctx_wrapper: RunContextWrapper[Any]
"""The run context."""
data: LocalShellCall
"""The data from the local shell tool call."""
LocalShellExecutor = Callable[[LocalShellCommandRequest], MaybeAwaitable[str]]
"""A function that executes a command on a shell."""
@dataclass
class LocalShellTool:
"""A tool that allows the LLM to execute commands on a shell.
For more details, see:
https://platform.openai.com/docs/guides/tools-local-shell
"""
executor: LocalShellExecutor
"""A function that executes a command on a shell."""
@property
def name(self):
return "local_shell"
class ShellToolLocalSkill(TypedDict):
"""Skill metadata for local shell environments."""
description: str
name: str
path: str
class ShellToolSkillReference(TypedDict):
"""Reference to a hosted shell skill."""
type: Literal["skill_reference"]
skill_id: str
version: NotRequired[str]
class ShellToolInlineSkillSource(TypedDict):
"""Inline skill source payload."""
data: str
media_type: Literal["application/zip"]
type: Literal["base64"]
class ShellToolInlineSkill(TypedDict):
"""Inline hosted shell skill bundle."""
description: str
name: str
source: ShellToolInlineSkillSource
type: Literal["inline"]
ShellToolContainerSkill = Union[ShellToolSkillReference, ShellToolInlineSkill]
"""Container skill configuration."""
class ShellToolContainerNetworkPolicyDomainSecret(TypedDict):
"""A secret bound to a single domain in allowlist mode."""
domain: str
name: str
value: str
class ShellToolContainerNetworkPolicyAllowlist(TypedDict):
"""Allowlist network policy for hosted containers."""
allowed_domains: list[str]
type: Literal["allowlist"]
domain_secrets: NotRequired[list[ShellToolContainerNetworkPolicyDomainSecret]]
class ShellToolContainerNetworkPolicyDisabled(TypedDict):
"""Disabled network policy for hosted containers."""
type: Literal["disabled"]
ShellToolContainerNetworkPolicy = Union[
ShellToolContainerNetworkPolicyAllowlist,
ShellToolContainerNetworkPolicyDisabled,
]
"""Network policy configuration for hosted shell containers."""
class ShellToolLocalEnvironment(TypedDict):
"""Local shell execution environment."""
type: Literal["local"]
skills: NotRequired[list[ShellToolLocalSkill]]
class ShellToolContainerAutoEnvironment(TypedDict):
"""Auto-provisioned hosted container environment."""
type: Literal["container_auto"]
file_ids: NotRequired[list[str]]
memory_limit: NotRequired[Literal["1g", "4g", "16g", "64g"] | None]
network_policy: NotRequired[ShellToolContainerNetworkPolicy]
skills: NotRequired[list[ShellToolContainerSkill]]
class ShellToolContainerReferenceEnvironment(TypedDict):
"""Reference to an existing hosted container."""
type: Literal["container_reference"]
container_id: str
ShellToolHostedEnvironment = Union[
ShellToolContainerAutoEnvironment,
ShellToolContainerReferenceEnvironment,
]
"""Hosted shell environment variants."""
ShellToolEnvironment = Union[ShellToolLocalEnvironment, ShellToolHostedEnvironment]
"""All supported shell environments."""
@dataclass
class ShellCallOutcome:
"""Describes the terminal condition of a shell command."""
type: Literal["exit", "timeout"]
exit_code: int | None = None
@dataclass
class ShellCommandOutput:
"""Structured output for a single shell command execution."""
stdout: str = ""
stderr: str = ""
outcome: ShellCallOutcome = field(default_factory=lambda: ShellCallOutcome(type="exit"))
command: str | None = None
provider_data: dict[str, Any] | None = None
@property
def exit_code(self) -> int | None:
return self.outcome.exit_code
@property
def status(self) -> Literal["completed", "timeout"]:
return "timeout" if self.outcome.type == "timeout" else "completed"
@dataclass
class ShellResult:
"""Result returned by a shell executor."""
output: list[ShellCommandOutput]
max_output_length: int | None = None
provider_data: dict[str, Any] | None = None
@dataclass
class ShellActionRequest:
"""Action payload for a next-generation shell call."""
commands: list[str]
timeout_ms: int | None = None
max_output_length: int | None = None
@dataclass
class ShellCallData:
"""Normalized shell call data provided to shell executors."""
call_id: str
action: ShellActionRequest
status: Literal["in_progress", "completed"] | None = None
raw: Any | None = None
@dataclass
class ShellCommandRequest:
"""A request to execute a modern shell call."""
ctx_wrapper: RunContextWrapper[Any]
data: ShellCallData
ShellExecutor = Callable[[ShellCommandRequest], MaybeAwaitable[Union[str, ShellResult]]]
"""Executes a shell command sequence and returns either text or structured output."""