@openai/agents-core
Version:
The OpenAI Agents SDK is a lightweight yet powerful framework for building multi-agent workflows.
914 lines (913 loc) • 41 kB
TypeScript
import type { Agent } from './agent';
import type { MCPTool } from './mcpShared';
import type { Computer } from './computer';
import type { Shell, ShellAction } from './shell';
import type { Editor, ApplyPatchOperation } from './editor';
import { JsonObjectSchema, JsonObjectSchemaNonStrict, JsonObjectSchemaStrict, UnknownContext } from './types';
import { RunContext } from './runContext';
import type { RunConfig } from './run';
import type { RunResult } from './result';
import { ToolTimeoutError } from './errors';
import { type InvalidToolInputDisposition } from './toolInputError';
import { type InvalidToolOutputFailure } from './toolOutputError';
import { RunToolApprovalItem, RunToolCallOutputItem } from './items';
import * as ProviderData from './types/providerData';
import * as protocol from './types/protocol';
import type { ZodInfer, ZodObjectLike } from './utils/zodCompat';
import type { StandardSchemaOutput, StandardSchemaWithJSON } from './utils/standardSchema';
import { ToolInputGuardrailDefinition, ToolOutputGuardrailDefinition, ToolInputGuardrailFunction, ToolOutputGuardrailFunction } from './toolGuardrail';
import type { ToolOutputCustomDataExtractor } from './utils/customData';
import { type ToolAllowedCallers } from './utils/toolCallers';
export type { ToolAllowedCaller, ToolAllowedCallers, } from './utils/toolCallers';
export type { ToolOutputCustomData } from './utils/customData';
export type { ToolOutputText, ToolOutputImage, ToolOutputFileContent, ToolCallStructuredOutput, ToolCallOutputContent, } from './types/protocol';
/**
* A function that determines if a tool call should be approved.
* Conditional policies receive an isolated copy of schema-normalized plain data.
* Outputs that cannot be copied as plain data are rejected before approval.
* Copyable arrays and primitives require manual approval instead of calling the
* policy. Validation can run application code before approval.
* After state restoration, the policy is evaluated again on the current
* normalized input before applying a manual decision for the same tool call.
* Return a plain object for conditional approval that must survive restoration;
* use `needsApproval: true` for durable manual approvals without a policy.
*
* @param runContext The current run context
* @param input The input to the tool
* @param callId The ID of the tool call
* @returns True if the tool call should be approved, false otherwise
*/
export type ToolApprovalFunction<TParameters extends ToolInputParameters> = (runContext: RunContext, input: ToolExecuteArgument<TParameters>, callId?: string) => Promise<boolean>;
export declare const FUNCTION_TOOL_PARSED_INPUT_CALLBACK: unique symbol;
export declare const FUNCTION_TOOL_INVALID_OUTPUT_FAILURE_CALLBACK: unique symbol;
export type FunctionToolPreparedInput = {
consumed: boolean;
input: string;
token: object;
validationMode: 'standard' | 'other';
disposition?: InvalidToolInputDisposition;
result: {
success: true;
value: any;
} | {
success: false;
error: unknown;
};
};
/** Prepare input for SDK runners through the internal utilities entry point. */
export declare function prepareFunctionToolInput(tool: Pick<FunctionTool<any, any, any>, 'invoke' | 'needsApproval'>, input: string): FunctionToolPreparedInput | undefined;
/** Attach prepared input for SDK runners through the internal utilities entry point. */
export declare function setFunctionToolPreparedInput(details: object, preparedInput: FunctionToolPreparedInput): void;
export declare function hasDynamicFunctionToolApprovalPolicy(tool: Pick<FunctionTool<any, any, any>, 'needsApproval'>): boolean;
export declare function hasInspectableFunctionToolArguments(value: unknown): value is Record<string, unknown>;
export type ToolCallDetails = {
toolCall?: protocol.FunctionCallItem;
resumeState?: string;
signal?: AbortSignal;
[FUNCTION_TOOL_PARSED_INPUT_CALLBACK]?: (input: unknown) => void;
[FUNCTION_TOOL_INVALID_OUTPUT_FAILURE_CALLBACK]?: (failure: InvalidToolOutputFailure) => void;
/**
* Internal: parent runner config for nested agent-tool runs (Agent.asTool).
*/
parentRunConfig?: Partial<RunConfig>;
};
export type FunctionToolCustomDataContext<Context = UnknownContext, TParameters extends ToolInputParameters = ToolInputParameters, Result = unknown> = {
runContext: RunContext<Context>;
tool: FunctionTool<Context, TParameters, Result>;
toolCall: protocol.FunctionCallItem;
input: unknown;
output: unknown;
rawItem: protocol.FunctionCallResultItem;
};
export type FunctionToolCustomDataExtractor<Context = UnknownContext, TParameters extends ToolInputParameters = ToolInputParameters, Result = unknown> = ToolOutputCustomDataExtractor<FunctionToolCustomDataContext<Context, TParameters, Result>>;
export type ComputerToolCustomDataContext<Context = UnknownContext, TComputer extends Computer = Computer> = {
runContext: RunContext<Context>;
tool: ComputerTool<Context, TComputer>;
toolCall: protocol.ComputerUseCallItem;
output: string;
rawItem: protocol.ComputerCallResultItem;
};
export type ComputerToolCustomDataExtractor<Context = UnknownContext, TComputer extends Computer = Computer> = ToolOutputCustomDataExtractor<ComputerToolCustomDataContext<Context, TComputer>>;
export type ApplyPatchToolCustomDataContext = {
runContext: RunContext;
tool: ApplyPatchTool;
operation: ApplyPatchOperation;
output: string;
status: protocol.ApplyPatchCallResultItem['status'];
rawItem: protocol.ApplyPatchCallResultItem;
};
export type ApplyPatchToolCustomDataExtractor = ToolOutputCustomDataExtractor<ApplyPatchToolCustomDataContext>;
export type FunctionToolTimeoutBehavior = 'error_as_result' | 'raise_exception';
export type ToolTimeoutErrorFunction<Context = UnknownContext, Result = string> = (context: RunContext<Context>, error: ToolTimeoutError, details?: ToolCallDetails) => Promise<Result> | Result;
export type ShellApprovalFunction = (runContext: RunContext, action: ShellAction, callId?: string) => Promise<boolean>;
export type ShellOnApprovalFunction = (runContext: RunContext, approvalItem: RunToolApprovalItem) => Promise<{
approve: boolean;
reason?: string;
}>;
export type ShellToolLocalSkill = {
description: string;
name: string;
path: string;
};
export type ShellToolSkillReference = {
type: 'skill_reference';
skillId: string;
version?: string;
};
export type ShellToolInlineSkillSource = {
data: string;
mediaType: 'application/zip';
type: 'base64';
};
export type ShellToolInlineSkill = {
description: string;
name: string;
source: ShellToolInlineSkillSource;
type: 'inline';
};
export type ShellToolContainerSkill = ShellToolSkillReference | ShellToolInlineSkill;
export type ShellToolContainerNetworkPolicyDomainSecret = {
domain: string;
name: string;
value: string;
};
export type ShellToolContainerNetworkPolicyAllowlist = {
allowedDomains: string[];
domainSecrets?: ShellToolContainerNetworkPolicyDomainSecret[];
type: 'allowlist';
};
export type ShellToolContainerNetworkPolicyDisabled = {
type: 'disabled';
};
export type ShellToolContainerNetworkPolicy = ShellToolContainerNetworkPolicyAllowlist | ShellToolContainerNetworkPolicyDisabled;
export type ShellToolLocalEnvironment = {
type: 'local';
skills?: ShellToolLocalSkill[];
};
export type ShellToolContainerAutoEnvironment = {
type: 'container_auto';
fileIds?: string[];
memoryLimit?: '1g' | '4g' | '16g' | '64g' | null;
networkPolicy?: ShellToolContainerNetworkPolicy;
skills?: ShellToolContainerSkill[];
};
export type ShellToolContainerReferenceEnvironment = {
type: 'container_reference';
containerId: string;
};
export type ShellToolHostedEnvironment = ShellToolContainerAutoEnvironment | ShellToolContainerReferenceEnvironment;
export type ShellToolEnvironment = ShellToolLocalEnvironment | ShellToolHostedEnvironment;
export type ApplyPatchApprovalFunction = (runContext: RunContext, operation: ApplyPatchOperation, callId?: string) => Promise<boolean>;
export type ApplyPatchOnApprovalFunction = (runContext: RunContext, approvalItem: RunToolApprovalItem) => Promise<{
approve: boolean;
reason?: string;
}>;
export type ComputerApprovalFunction = (runContext: RunContext, action: protocol.ComputerAction, callId?: string) => Promise<boolean>;
export type ComputerSafetyCheck = {
id: string;
code: string;
message?: string;
[key: string]: unknown;
};
/**
* Return true to acknowledge all pending checks, or false to reject the computer
* call without executing it. Rejection returns a tool result and lets the run
* continue. Returning void leaves the checks unacknowledged and allows execution.
*/
export type ComputerSafetyCheckResult = void | boolean | {
acknowledgedSafetyChecks: ComputerSafetyCheck[];
} | {
acknowledged_safety_checks: ComputerSafetyCheck[];
};
export type ComputerOnSafetyCheckFunction = (args: {
runContext: RunContext;
pendingSafetyChecks: ComputerSafetyCheck[];
toolCall: protocol.ComputerUseCallItem;
}) => Promise<ComputerSafetyCheckResult>;
export type ToolEnabledFunction<Context = UnknownContext> = (runContext: RunContext<Context>, agent: Agent<any, any>) => Promise<boolean>;
type ToolEnabledPredicate<Context = UnknownContext> = (args: {
runContext: RunContext<Context>;
agent: Agent<any, any>;
}) => boolean | Promise<boolean>;
type ToolEnabledOption<Context = UnknownContext> = boolean | ToolEnabledPredicate<Context>;
/**
* Exposes a function to the agent as a tool to be called
*
* @param Context The context of the tool
* @param Result The result of the tool
*/
export type FunctionTool<Context = UnknownContext, TParameters extends ToolInputParameters = undefined, Result = unknown> = {
type: 'function';
/**
* The name of the tool.
*/
name: string;
/**
* The description of the tool that helps the model to understand when to use the tool
*/
description: string;
/**
* A JSON schema describing the parameters of the tool.
*/
parameters: JsonObjectSchema<any>;
/**
* Whether the tool is strict. If true, the model must try to strictly follow the schema (might result in slower response times).
*/
strict: boolean;
/**
* Responses API only. Hides a top-level function tool definition until tool search loads it.
*/
deferLoading?: boolean;
/**
* A fresh copy of the untrusted annotations supplied by the MCP server at discovery.
* Absent for ordinary function tools and when the server omits annotations.
* Missing hints stay omitted. The application decides which servers to trust
* and when to approve or retry a call.
*/
readonly mcpAnnotations?: Readonly<NonNullable<MCPTool['annotations']>>;
/**
* Additional provider-specific metadata forwarded with the function tool definition.
*/
providerData?: Record<string, any>;
/**
* Responses API only. Controls which execution contexts can invoke the tool.
* When omitted, the Responses API defaults to direct calls only.
*/
allowedCallers?: ToolAllowedCallers;
/**
* Responses API only. Describes the JSON value encoded in string outputs.
* Zod schemas also validate the tool result at runtime.
*/
outputSchema?: JsonObjectSchema<any>;
/**
* The function to invoke when the tool is called.
*/
invoke: (runContext: RunContext<Context>, input: string, details?: ToolCallDetails) => Promise<string | Result>;
/**
* Optional model-visible fallback for execution errors and pre-execution
* failures. Structured tools use this to preserve their output contract.
*/
errorFunction?: ToolErrorFunction<Context, string | Result> | null;
/**
* Whether the tool needs human approval before it can be called. If this is true, the run will result in an `interruption` that the
* program has to resolve by approving or rejecting the tool call.
*/
needsApproval: ToolApprovalFunction<TParameters>;
/**
* Optional timeout in milliseconds for each tool invocation.
*/
timeoutMs?: number;
/**
* Defines how timeout errors are handled.
*
* - `error_as_result`: return a model-visible timeout message.
* - `raise_exception`: raise `ToolTimeoutError` and fail the run.
*
* Tools created with an output schema default to `raise_exception`; other
* function tools default to `error_as_result`.
*/
timeoutBehavior?: FunctionToolTimeoutBehavior;
/**
* Optional formatter for timeout errors when timeoutBehavior is `error_as_result`.
*/
timeoutErrorFunction?: ToolTimeoutErrorFunction<Context, Result>;
/**
* Determines whether the tool should be made available to the model for the current run.
*/
isEnabled: ToolEnabledFunction<Context>;
/**
* Guardrails that run before the tool executes.
*/
inputGuardrails?: ToolInputGuardrailDefinition<Context>[];
/**
* Guardrails that run after the tool executes.
*/
outputGuardrails?: ToolOutputGuardrailDefinition<Context>[];
/**
* Optional callback that attaches SDK-only custom data to the emitted tool output item.
*/
customDataExtractor?: FunctionToolCustomDataExtractor<Context, TParameters, Result>;
};
/**
* Arguments provided to computer initializers.
*/
export type ComputerInitializerArgs<Context = UnknownContext> = {
runContext: RunContext<Context>;
};
/**
* A function that initializes a computer for the current run.
*/
type BivariantComputerCreate<Context = UnknownContext, TComputer extends Computer = Computer> = {
bivarianceHack: (args: ComputerInitializerArgs<Context>) => TComputer | Promise<TComputer>;
}['bivarianceHack'];
export type ComputerCreate<Context = UnknownContext, TComputer extends Computer = Computer> = BivariantComputerCreate<Context, TComputer>;
/**
* Optional cleanup invoked after a run finishes when the computer was created via an initializer.
*/
type BivariantComputerDispose<Context = UnknownContext, TComputer extends Computer = Computer> = {
bivarianceHack: (args: ComputerInitializerArgs<Context> & {
computer: TComputer;
}) => void | Promise<void>;
}['bivarianceHack'];
export type ComputerDispose<Context = UnknownContext, TComputer extends Computer = Computer> = BivariantComputerDispose<Context, TComputer>;
/**
* Initializes a computer for the current run and optionally tears it down after the run.
*/
export type ComputerProvider<Context = UnknownContext, TComputer extends Computer = Computer> = {
create: ComputerCreate<Context, TComputer>;
dispose?: ComputerDispose<Context, TComputer>;
};
type ComputerInitializer<Context = UnknownContext, TComputer extends Computer = Computer> = ComputerCreate<Context, TComputer> | ComputerProvider<Context, TComputer>;
export type ComputerConfig<Context = UnknownContext, TComputer extends Computer = Computer> = Computer | ComputerInitializer<Context, TComputer>;
/**
* Exposes a computer to the model as a tool to be called
*
* @param Context The context of the tool
* @param Result The result of the tool
*/
export type ComputerTool<Context = UnknownContext, TComputer extends Computer = Computer> = {
type: 'computer';
/**
* The name of the tool.
*/
name: 'computer_use_preview' | (string & {});
/**
* The computer to use.
*/
computer: ComputerConfig<Context, TComputer>;
/**
* Predicate determining whether this computer action requires approval.
*/
needsApproval: ComputerApprovalFunction;
/**
* Optional handler invoked before execution when the model reports pending safety checks.
* If omitted, the checks remain unacknowledged and execution continues with a warning.
* Return false to reject the call, or true to acknowledge all checks.
* Returning void allows execution without acknowledgment.
*/
onSafetyCheck?: ComputerOnSafetyCheckFunction;
/**
* Optional callback that attaches SDK-only custom data to the emitted tool output item.
*/
customDataExtractor?: ComputerToolCustomDataExtractor<Context, TComputer>;
};
/**
* Exposes a computer to the agent as a tool to be called.
*
* @param options Additional configuration for the computer tool like specifying the location of your agent
* @returns a computer tool definition
*/
export declare function computerTool<Context = UnknownContext, TComputer extends Computer = Computer>(options: {
name?: string;
computer: ComputerConfig<Context, TComputer>;
needsApproval?: boolean | ComputerApprovalFunction;
onSafetyCheck?: ComputerOnSafetyCheckFunction;
customDataExtractor?: ComputerToolCustomDataExtractor<Context, TComputer>;
}): ComputerTool<Context, TComputer>;
type ShellToolBase = {
type: 'shell';
/**
* Public name exposed to the model. Defaults to `shell`.
*/
name: string;
/**
* Predicate determining whether this shell action requires approval.
*/
needsApproval: ShellApprovalFunction;
/**
* Optional handler to auto-approve or reject when approval is required.
* If provided, it will be invoked immediately when an approval is needed.
*/
onApproval?: ShellOnApprovalFunction;
/**
* Responses API only. Controls which execution contexts can invoke the tool.
*/
allowedCallers?: ToolAllowedCallers;
};
type LocalShellTool = ShellToolBase & {
/**
* Optional for backward compatibility with direct `ShellTool` literals.
* When omitted, local mode is assumed.
*/
environment?: ShellToolLocalEnvironment;
/**
* The shell implementation to execute commands in local mode.
*/
shell: Shell;
};
type NormalizedLocalShellTool = Omit<LocalShellTool, 'environment'> & {
environment: ShellToolLocalEnvironment;
};
type HostedShellTool = ShellToolBase & {
environment: ShellToolHostedEnvironment;
/**
* Hosted environments do not accept local shell implementations.
*/
shell?: never;
};
export type ShellTool = LocalShellTool | HostedShellTool;
type LocalShellToolOptions = {
name?: string;
environment?: ShellToolLocalEnvironment;
shell: Shell;
needsApproval?: boolean | ShellApprovalFunction;
onApproval?: ShellOnApprovalFunction;
allowedCallers?: ToolAllowedCallers;
};
type HostedShellToolOptions = {
name?: string;
environment: ShellToolHostedEnvironment;
shell?: never;
needsApproval?: never;
onApproval?: never;
allowedCallers?: ToolAllowedCallers;
};
export declare function shellTool(options: LocalShellToolOptions): NormalizedLocalShellTool;
export declare function shellTool(options: HostedShellToolOptions): HostedShellTool;
export type ApplyPatchTool = {
type: 'apply_patch';
/**
* Public name exposed to the model. Defaults to `apply_patch`.
*/
name: string;
/**
* Diff applier invoked when the tool is called.
*/
editor: Editor;
/**
* Predicate determining whether this apply_patch operation requires approval.
*/
needsApproval: ApplyPatchApprovalFunction;
/**
* Optional handler to auto-approve or reject when approval is required.
*/
onApproval?: ApplyPatchOnApprovalFunction;
/**
* Responses API only. Controls which execution contexts can invoke the tool.
*/
allowedCallers?: ToolAllowedCallers;
/**
* Optional callback that attaches SDK-only custom data to the emitted tool output item.
*/
customDataExtractor?: ApplyPatchToolCustomDataExtractor;
};
export declare function applyPatchTool(options: Partial<Omit<ApplyPatchTool, 'type' | 'editor' | 'needsApproval'>> & {
editor: Editor;
needsApproval?: boolean | ApplyPatchApprovalFunction;
onApproval?: ApplyPatchOnApprovalFunction;
customDataExtractor?: ApplyPatchToolCustomDataExtractor;
}): ApplyPatchTool;
export type HostedMCPApprovalFunction<Context = UnknownContext> = (context: RunContext<Context>, data: RunToolApprovalItem) => Promise<{
approve: boolean;
reason?: string;
}>;
/**
* A hosted MCP tool that lets the model call a remote MCP server directly
* without a round trip back to your code.
*/
export type HostedMCPTool<Context = UnknownContext> = HostedTool & {
name: 'hosted_mcp';
providerData: ProviderData.HostedMCPTool<Context>;
};
/**
* Creates a hosted MCP tool definition.
*
* @param options - Configuration for the hosted MCP tool, including server connection details
* and approval requirements.
*/
export declare function hostedMcpTool<Context = UnknownContext>(options: {
allowedTools?: string[] | {
toolNames?: string[];
};
allowedCallers?: ToolAllowedCallers;
deferLoading?: boolean;
serverDescription?: string;
} & ({
serverLabel: string;
serverUrl?: string;
authorization?: string;
headers?: Record<string, string>;
} | {
serverLabel: string;
connectorId: string;
authorization?: string;
headers?: Record<string, string>;
}) & ({
requireApproval?: never;
} | {
requireApproval: 'never';
} | {
requireApproval: 'always' | {
never?: {
toolNames?: string[];
readOnly?: boolean;
};
always?: {
toolNames?: string[];
readOnly?: boolean;
};
};
onApproval?: HostedMCPApprovalFunction<Context>;
})): HostedMCPTool<Context>;
/**
* A built-in hosted tool that will be executed directly by the model during the request and won't result in local code executions.
* Examples of these are `web_search_call` or `file_search_call`.
*
* @param Context The context of the tool
* @param Result The result of the tool
*/
export type HostedTool = {
type: 'hosted_tool';
/**
* A unique name for the tool.
*/
name: string;
/**
* Additional configuration data that gets passed to the tool
*/
providerData?: Record<string, any>;
};
export type ClientToolSearchLoadDefaultFunction<Context = UnknownContext> = (paths: string[]) => Tool<Context>[];
export type ClientToolSearchExecutorArgs<Context = UnknownContext> = {
agent: Agent<Context, any>;
availableTools: Tool<Context>[];
loadDefault: ClientToolSearchLoadDefaultFunction<Context>;
runContext: RunContext<Context>;
toolCall: protocol.ToolSearchCallItem;
};
export type ClientToolSearchExecutorResult<Context = UnknownContext> = Tool<Context> | Tool<Context>[] | null | undefined;
export type ClientToolSearchExecutor<Context = UnknownContext> = (args: ClientToolSearchExecutorArgs<Context>) => ClientToolSearchExecutorResult<Context> | Promise<ClientToolSearchExecutorResult<Context>>;
export declare const CLIENT_TOOL_SEARCH_EXECUTOR: unique symbol;
export declare function attachClientToolSearchExecutor<Context = UnknownContext>(tool: HostedTool, executor: ClientToolSearchExecutor<Context>): HostedTool;
export declare function getClientToolSearchExecutor<Context = UnknownContext>(tool: Tool<Context>): ClientToolSearchExecutor<Context> | undefined;
export declare function getToolSearchRuntimeToolKey<Context = UnknownContext>(tool: Tool<Context>): string | undefined;
/**
* A tool that can be called by the model.
* @template Context The context passed to the tool
*/
export type Tool<Context = unknown> = FunctionTool<Context, any, any> | ComputerTool<Context, any> | ShellTool | ApplyPatchTool | HostedTool;
/**
* The result of invoking a function tool. Either the actual output of the execution or a tool
* approval request.
*
* These get passed for example to the `toolUseBehavior` option of the `Agent` constructor.
*/
export type FunctionToolResult<Context = UnknownContext, TParameters extends ToolInputParameters = any, Result = any> = {
type: 'function_output';
/**
* The tool that was called.
*/
tool: FunctionTool<Context, TParameters, Result>;
/**
* The output of the tool call. This can be a string or a stringifable item.
*/
output: string | unknown;
/**
* The run item representing the tool call output.
*/
runItem: RunToolCallOutputItem;
/**
* The result returned when the tool execution runs another agent. Populated when the
* invocation originated from {@link Agent.asTool} and the nested agent completed a run.
*/
agentRunResult?: RunResult<Context, Agent<Context, any>>;
/**
* Any interruptions collected while the nested agent executed. These are surfaced to allow
* callers to pause and resume workflows that require approvals.
*/
interruptions?: RunToolApprovalItem[];
} | {
/**
* Indicates that the tool requires approval before it can be called.
*/
type: 'function_approval';
/**
* The tool that is requiring to be approved.
*/
tool: FunctionTool<Context, TParameters, Result>;
/**
* The item representing the tool call that is requiring approval.
*/
runItem: RunToolApprovalItem;
} | {
/**
* Indicates that the tool requires approval before it can be called.
*/
type: 'hosted_mcp_tool_approval';
/**
* The tool that is requiring to be approved.
*/
tool: HostedMCPTool<Context>;
/**
* The item representing the tool call that is requiring approval.
*/
runItem: RunToolApprovalItem;
};
/**
* The parameters of a tool.
*
* This can be a supported Standard Schema, a Zod schema, a JSON schema or undefined.
*
* If a supported Standard Schema or Zod schema is provided, the arguments to the tool will
* automatically be parsed and validated against the schema.
*
* If a JSON schema is provided, the arguments to the tool will be passed as is.
*
* If undefined is provided, the arguments to the tool will be passed as a string.
*/
export type ToolInputParameters = undefined | ZodObjectLike | StandardSchemaWithJSON<any, any> | JsonObjectSchema<any>;
/**
* The parameters of a tool that has strict mode enabled.
*
* This can be a supported Standard Schema, a Zod schema, a JSON schema or undefined.
*
* If a supported Standard Schema or Zod schema is provided, the arguments to the tool will
* automatically be parsed and validated against the schema.
*
* If a JSON schema is provided, the arguments to the tool will be parsed as JSON but not validated.
*
* If undefined is provided, the arguments to the tool will be passed as a string.
*/
export type ToolInputParametersStrict = undefined | ZodObjectLike | StandardSchemaWithJSON<any, any> | JsonObjectSchemaStrict<any>;
/**
* The parameters of a tool that has strict mode disabled.
*
* If a JSON schema is provided, the arguments to the tool will be parsed as JSON but not validated.
*
* Zod schemas are not supported without strict: true.
*/
export type ToolInputParametersNonStrict = undefined | JsonObjectSchemaNonStrict<any>;
/**
* A schema describing the JSON object encoded in a function tool output.
*
* Zod schemas are converted to JSON Schema when the tool is created. Plain
* JSON Schema objects are passed through unchanged.
*/
export type ToolOutputSchema = ZodObjectLike | JsonObjectSchema<any>;
type ToolExecuteResult<TOutputSchema extends ToolOutputSchema | undefined, Result> = TOutputSchema extends ZodObjectLike ? ZodInfer<TOutputSchema> : TOutputSchema extends JsonObjectSchema<any> ? unknown : Result;
type ToolFallbackResult<TOutputSchema extends ToolOutputSchema | undefined> = TOutputSchema extends undefined ? string : ToolExecuteResult<TOutputSchema, unknown>;
/**
* The arguments to a tool.
*
* The type of the arguments are derived from the parameters passed to the tool definition.
*
* If the parameters are passed as a JSON schema the type is `unknown`. For Standard Schema and
* Zod schemas it will match the inferred validation output type. Otherwise the type is `string`.
*/
export type ToolExecuteArgument<TParameters extends ToolInputParameters> = TParameters extends StandardSchemaWithJSON<any, any> ? StandardSchemaOutput<TParameters> : TParameters extends ZodObjectLike ? ZodInfer<TParameters> : TParameters extends JsonObjectSchema<any> ? unknown : string;
/**
* The function to invoke when the tool is called.
*
* @param input The arguments to the tool (see ToolExecuteArgument)
* @param context An instance of the current RunContext
*/
type ToolExecuteFunction<TParameters extends ToolInputParameters, Context = UnknownContext, Result = unknown> = (input: ToolExecuteArgument<TParameters>, context?: RunContext<Context>, details?: ToolCallDetails) => Promise<Result> | Result;
/**
* The function to invoke when an error or model-visible pre-execution rejection
* occurs. This can provide additional context or a fallback value.
*
* @param context An instance of the current RunContext
* @param error The error that occurred
*/
type ToolErrorFunction<Context = UnknownContext, Result = string> = (context: RunContext<Context>, error: Error | unknown, details?: ToolCallDetails) => Promise<Result> | Result;
type ToolTimeoutOptions<Context, TOutputSchema extends ToolOutputSchema | undefined> = [TOutputSchema] extends [undefined] ? {
/** Optional timeout in milliseconds for each tool call. */
timeoutMs?: number;
/** Determines whether a timeout becomes a result or an exception. */
timeoutBehavior?: FunctionToolTimeoutBehavior;
/** Optional formatter for model-visible timeout results. */
timeoutErrorFunction?: ToolTimeoutErrorFunction<Context, string>;
} : {
/** Optional timeout in milliseconds for each tool call. */
timeoutMs?: number;
/** Structured tools raise timeout exceptions by default. */
timeoutBehavior?: 'raise_exception';
timeoutErrorFunction?: never;
} | {
/** Optional timeout in milliseconds for each tool call. */
timeoutMs?: number;
/** Return a schema-compatible timeout result. */
timeoutBehavior: 'error_as_result';
/** Required formatter for schema-compatible timeout results. */
timeoutErrorFunction: ToolTimeoutErrorFunction<Context, ToolFallbackResult<TOutputSchema>>;
};
type ToolGuardrailOptions<Context = UnknownContext> = {
/**
* Guardrails that validate or block tool invocation before it runs.
*/
inputGuardrails?: ToolInputGuardrailDefinition<Context>[] | {
name: string;
run: ToolInputGuardrailFunction<Context>;
}[];
/**
* Guardrails that validate or alter tool output after it runs.
*/
outputGuardrails?: ToolOutputGuardrailDefinition<Context>[] | {
name: string;
run: ToolOutputGuardrailFunction<Context>;
}[];
};
/**
* The options for a tool that has strict mode enabled.
*
* @param TParameters The parameters of the tool
* @param Context The context of the tool
*/
type StrictToolOptionsBase<TParameters extends ToolInputParametersStrict, Context = UnknownContext, TOutputSchema extends ToolOutputSchema | undefined = undefined> = {
/**
* The name of the tool. Must be unique within the agent.
*/
name?: string;
/**
* The description of the tool. This is used to help the model understand when to use the tool.
*/
description: string;
/**
* A supported Standard Schema, Zod schema, or JSON schema describing the parameters of the tool.
* Standard Schema and Zod parameters are automatically parsed and validated synchronously.
*/
parameters: TParameters;
/**
* Whether the tool is strict. If true, the model must try to strictly follow the schema (might result in slower response times).
*/
strict?: true;
/**
* Responses API only. Hides a top-level function tool definition until tool search loads it.
*/
deferLoading?: boolean;
/**
* Additional provider-specific metadata forwarded with the function tool definition.
*/
providerData?: Record<string, any>;
/**
* Responses API only. Controls which execution contexts can invoke the tool.
*/
allowedCallers?: ToolAllowedCallers;
/**
* Responses API only. Describes the JSON object encoded in string outputs.
* Zod object schemas are converted to JSON Schema and constrain the return
* type of `execute` to the inferred Zod output type. They also validate the
* result at runtime.
*/
outputSchema?: TOutputSchema;
/**
* The function to invoke when the tool is called.
*/
execute: ToolExecuteFunction<TParameters, Context, ToolExecuteResult<TOutputSchema, unknown>>;
/**
* The function to invoke when an error or model-visible pre-execution
* rejection occurs. Tools with an output schema rethrow by default so they
* cannot emit an unstructured error string. Provide this callback to return
* a schema-compatible fallback. Without an output schema, the default returns
* a fixed generic error message. For failures handled during tool invocation,
* provide this callback for application-approved details, or set it to `null`
* to propagate the error. Without an output schema, `Runner` handles malformed
* JSON before invoking the tool and returns fixed feedback without calling this
* callback, even when it is `null`.
*/
errorFunction?: ToolErrorFunction<Context, ToolFallbackResult<TOutputSchema>> | null;
/**
* Whether the tool needs human approval before it can be called. If this is true, the run will result in an `interruption` that the
* program has to resolve by approving or rejecting the tool call.
*/
needsApproval?: boolean | ToolApprovalFunction<TParameters>;
/**
* Determines whether the tool should be exposed to the model for the current run.
*/
isEnabled?: ToolEnabledOption<Context>;
/**
* Optional callback that attaches SDK-only custom data to the emitted tool output item.
*/
customDataExtractor?: FunctionToolCustomDataExtractor<Context, TParameters, ToolExecuteResult<TOutputSchema, unknown>>;
};
type StrictToolOptions<TParameters extends ToolInputParametersStrict, Context = UnknownContext, TOutputSchema extends ToolOutputSchema | undefined = undefined> = StrictToolOptionsBase<TParameters, Context, TOutputSchema> & ToolGuardrailOptions<Context> & ToolTimeoutOptions<Context, TOutputSchema>;
/**
* The options for a tool that has strict mode disabled.
*
* @param TParameters The parameters of the tool
* @param Context The context of the tool
*/
type NonStrictToolOptionsBase<TParameters extends ToolInputParametersNonStrict, Context = UnknownContext, TOutputSchema extends ToolOutputSchema | undefined = undefined> = {
/**
* The name of the tool. Must be unique within the agent.
*/
name?: string;
/**
* The description of the tool. This is used to help the model understand when to use the tool.
*/
description: string;
/**
* A JSON schema of the tool. To use a Zod schema, you need to use a `strict` schema.
*/
parameters: TParameters;
/**
* Whether the tool is strict If true, the model must try to strictly follow the schema (might result in slower response times).
*/
strict: false;
/**
* Responses API only. Hides a top-level function tool definition until tool search loads it.
*/
deferLoading?: boolean;
/**
* Additional provider-specific metadata forwarded with the function tool definition.
*/
providerData?: Record<string, any>;
/**
* Responses API only. Controls which execution contexts can invoke the tool.
*/
allowedCallers?: ToolAllowedCallers;
/**
* Responses API only. Describes the JSON object encoded in string outputs.
* Zod object schemas are converted to JSON Schema and constrain the return
* type of `execute` to the inferred Zod output type. They also validate the
* result at runtime.
*/
outputSchema?: TOutputSchema;
/**
* The function to invoke when the tool is called.
*/
execute: ToolExecuteFunction<TParameters, Context, ToolExecuteResult<TOutputSchema, unknown>>;
/**
* The function to invoke when an error or model-visible pre-execution
* rejection occurs. Tools with an output schema rethrow by default so they
* cannot emit an unstructured error string. Provide this callback to return
* a schema-compatible fallback. Without an output schema, the default returns
* a fixed generic error message. For failures handled during tool invocation,
* provide this callback for application-approved details, or set it to `null`
* to propagate the error. Without an output schema, `Runner` handles malformed
* JSON before invoking the tool and returns fixed feedback without calling this
* callback, even when it is `null`.
*/
errorFunction?: ToolErrorFunction<Context, ToolFallbackResult<TOutputSchema>> | null;
/**
* Whether the tool needs human approval before it can be called. If this is true, the run will result in an `interruption` that the
* program has to resolve by approving or rejecting the tool call.
*/
needsApproval?: boolean | ToolApprovalFunction<TParameters>;
/**
* Determines whether the tool should be exposed to the model for the current run.
*/
isEnabled?: ToolEnabledOption<Context>;
/**
* Optional callback that attaches SDK-only custom data to the emitted tool output item.
*/
customDataExtractor?: FunctionToolCustomDataExtractor<Context, TParameters, ToolExecuteResult<TOutputSchema, unknown>>;
};
type NonStrictToolOptions<TParameters extends ToolInputParametersNonStrict, Context = UnknownContext, TOutputSchema extends ToolOutputSchema | undefined = undefined> = NonStrictToolOptionsBase<TParameters, Context, TOutputSchema> & ToolGuardrailOptions<Context> & ToolTimeoutOptions<Context, TOutputSchema>;
/**
* The options for a tool.
*
* @param TParameters The parameters of the tool
* @param Context The context of the tool
*/
export type ToolOptions<TParameters extends ToolInputParameters, Context = UnknownContext, TOutputSchema extends ToolOutputSchema | undefined = undefined> = StrictToolOptions<Extract<TParameters, ToolInputParametersStrict>, Context, TOutputSchema> | NonStrictToolOptions<Extract<TParameters, ToolInputParametersNonStrict>, Context, TOutputSchema>;
export type ToolOptionsWithGuardrails<TParameters extends ToolInputParameters, Context = UnknownContext, TOutputSchema extends ToolOutputSchema | undefined = undefined> = ToolOptions<TParameters, Context, TOutputSchema>;
type AnyFunctionTool = FunctionTool<any, any, any>;
type FunctionToolInvocationArgs<Context = UnknownContext, TParameters extends ToolInputParameters = ToolInputParameters, Result = unknown> = {
tool: FunctionTool<Context, TParameters, Result>;
runContext: RunContext<Context>;
input: string;
details?: ToolCallDetails;
};
/**
* Validate a function tool output when the tool was created with a runtime
* output schema.
*/
export declare function validateFunctionToolOutput<Context = UnknownContext, TParameters extends ToolInputParameters = ToolInputParameters, Result = unknown>(args: {
tool: FunctionTool<Context, TParameters, Result>;
output: unknown;
runContext: RunContext<Context>;
details?: ToolCallDetails;
}): unknown;
/**
* Invoke a function tool while enforcing optional per-tool timeout settings.
*/
export declare function invokeFunctionTool<Context = UnknownContext, TParameters extends ToolInputParameters = ToolInputParameters, Result = unknown>(args: FunctionToolInvocationArgs<Context, TParameters, Result>): Promise<string | Result>;
/**
* Exposes a function to the agent as a tool to be called
*
* @param options The options for the tool
* @returns A new tool
*/
export declare function tool<TParameters extends ToolInputParameters = undefined, Context = UnknownContext, Result = string, TOutputSchema extends ToolOutputSchema | undefined = undefined>(options: ToolOptions<TParameters, Context, TOutputSchema>): FunctionTool<Context, TParameters, ToolExecuteResult<TOutputSchema, Result>>;
export type ToolNamespaceOptions<TTools extends readonly AnyFunctionTool[] = readonly AnyFunctionTool[]> = {
/**
* The namespace name to expose to the model.
*/
name: string;
/**
* Description shared by all tools in the namespace.
*/
description: string;
/**
* Function tools to attach to the namespace.
*/
tools: TTools;
};
/**
* Responses API only. Group function tools under a shared namespace.
*
* @param options - Namespace metadata and function tools to attach.
* @returns shallow-cloned function tools carrying namespace metadata.
*/
export declare function toolNamespace<TTools extends readonly AnyFunctionTool[]>(options: ToolNamespaceOptions<TTools>): TTools;