跳转到内容

pydantic_ai.tools

AgentDepsT 模块属性

AgentDepsT = TypeVar(
    "AgentDepsT", default=None, contravariant=True
)

代理依赖项的类型变量。

RunContext 数据类

基类:Generic[AgentDepsT]

关于当前调用的信息。

源代码位于 pydantic_ai_slim/pydantic_ai/_run_context.py
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
@dataclasses.dataclass(repr=False, kw_only=True)
class RunContext(Generic[AgentDepsT]):
    """Information about the current call."""

    deps: AgentDepsT
    """Dependencies for the agent."""
    model: Model
    """The model used in this run."""
    usage: RunUsage
    """LLM usage associated with the run."""
    prompt: str | Sequence[_messages.UserContent] | None = None
    """The original user prompt passed to the run."""
    messages: list[_messages.ModelMessage] = field(default_factory=list)
    """Messages exchanged in the conversation so far."""
    tracer: Tracer = field(default_factory=NoOpTracer)
    """The tracer to use for tracing the run."""
    trace_include_content: bool = False
    """Whether to include the content of the messages in the trace."""
    retries: dict[str, int] = field(default_factory=dict)
    """Number of retries for each tool so far."""
    tool_call_id: str | None = None
    """The ID of the tool call."""
    tool_name: str | None = None
    """Name of the tool being called."""
    retry: int = 0
    """Number of retries so far."""
    run_step: int = 0
    """The current step in the run."""
    tool_call_approved: bool = False
    """Whether a tool call that required approval has now been approved."""

    __repr__ = _utils.dataclasses_no_defaults_repr

deps 实例属性

deps: AgentDepsT

代理的依赖项。

model 实例属性

model: Model

本次运行中使用的模型。

usage 实例属性

usage: RunUsage

与本次运行相关的LLM使用情况。

prompt 类属性 实例属性

prompt: str | Sequence[UserContent] | None = None

传递给本次运行的原始用户提示。

messages 类属性 实例属性

messages: list[ModelMessage] = field(default_factory=list)

到目前为止在对话中交换的消息。

tracer 类属性 实例属性

tracer: Tracer = field(default_factory=NoOpTracer)

用于追踪本次运行的追踪器。

trace_include_content 类属性 实例属性

trace_include_content: bool = False

是否在追踪中包含消息内容。

retries 类属性 实例属性

retries: dict[str, int] = field(default_factory=dict)

到目前为止每个工具的重试次数。

tool_call_id 类属性 实例属性

tool_call_id: str | None = None

工具调用的ID。

tool_name 类属性 实例属性

tool_name: str | None = None

正在调用的工具的名称。

retry 类属性 实例属性

retry: int = 0

到目前为止的重试次数。

run_step 类属性 实例属性

run_step: int = 0

运行中的当前步骤。

tool_call_approved 类属性 实例属性

tool_call_approved: bool = False

一个需要审批的工具调用现在是否已被批准。

ToolParams 模块属性

ToolParams = ParamSpec('ToolParams', default=...)

检索函数参数规范。

SystemPromptFunc 模块属性

一个函数,它可能接受也可能不接受 RunContext 作为参数,并且可能是也可能不是异步的。

用法 SystemPromptFunc[AgentDepsT]

ToolFuncContext 模块属性

一个将 RunContext 作为第一个参数的工具函数。

用法 ToolContextFunc[AgentDepsT, ToolParams]

ToolFuncPlain 模块属性

ToolFuncPlain: TypeAlias = Callable[ToolParams, Any]

一个不将 RunContext 作为第一个参数的工具函数。

用法 ToolPlainFunc[ToolParams]

ToolFuncEither 模块属性

两种工具函数中的任意一种。

这只是 ToolFuncContextToolFuncPlain 的联合体。

用法 ToolFuncEither[AgentDepsT, ToolParams]

ToolPrepareFunc 模块属性

ToolPrepareFunc: TypeAlias = Callable[
    [RunContext[AgentDepsT], "ToolDefinition"],
    Awaitable["ToolDefinition | None"],
]

可以在调用时准备工具定义的函数的定义。

更多信息请参见工具文档

示例 — 此处 only_if_42 作为 ToolPrepareFunc 是有效的

from pydantic_ai import RunContext, Tool
from pydantic_ai.tools import ToolDefinition

async def only_if_42(
    ctx: RunContext[int], tool_def: ToolDefinition
) -> ToolDefinition | None:
    if ctx.deps == 42:
        return tool_def

def hitchhiker(ctx: RunContext[int], answer: str) -> str:
    return f'{ctx.deps} {answer}'

hitchhiker = Tool(hitchhiker, prepare=only_if_42)

用法 ToolPrepareFunc[AgentDepsT]

ToolsPrepareFunc 模块属性

ToolsPrepareFunc: TypeAlias = Callable[
    [RunContext[AgentDepsT], list["ToolDefinition"]],
    Awaitable["list[ToolDefinition] | None"],
]

一个函数的定义,该函数可以为每个步骤准备所有工具的定义。如果您想自定义多个工具的定义,或者想为给定步骤注册一部分工具,这将非常有用。

示例 — 此处 turn_on_strict_if_openai 作为 ToolsPrepareFunc 是有效的

from dataclasses import replace

from pydantic_ai import Agent, RunContext
from pydantic_ai.tools import ToolDefinition


async def turn_on_strict_if_openai(
    ctx: RunContext[None], tool_defs: list[ToolDefinition]
) -> list[ToolDefinition] | None:
    if ctx.model.system == 'openai':
        return [replace(tool_def, strict=True) for tool_def in tool_defs]
    return tool_defs

agent = Agent('openai:gpt-4o', prepare_tools=turn_on_strict_if_openai)

用法 ToolsPrepareFunc[AgentDepsT]

DocstringFormat 模块属性

DocstringFormat: TypeAlias = Literal[
    "google", "numpy", "sphinx", "auto"
]

支持的文档字符串格式。

  • 'google'Google 风格的文档字符串。
  • 'numpy'Numpy 风格的文档字符串。
  • 'sphinx'Sphinx 风格的文档字符串。
  • 'auto' — 根据文档字符串的结构自动推断格式。

DeferredToolRequests 数据类

需要批准或外部执行的工具调用。

这可以用作代理的 output_type,如果模型调用了任何延迟工具,它将用作代理运行的输出。

结果可以通过带有相同工具调用 ID 的 DeferredToolResults 对象传递给下一个代理运行。

更多信息请参见延迟工具文档

源代码位于 pydantic_ai_slim/pydantic_ai/tools.py
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
@dataclass(kw_only=True)
class DeferredToolRequests:
    """Tool calls that require approval or external execution.

    This can be used as an agent's `output_type` and will be used as the output of the agent run if the model called any deferred tools.

    Results can be passed to the next agent run using a [`DeferredToolResults`][pydantic_ai.tools.DeferredToolResults] object with the same tool call IDs.

    See [deferred tools docs](../deferred-tools.md#deferred-tools) for more information.
    """

    calls: list[ToolCallPart] = field(default_factory=list)
    """Tool calls that require external execution."""
    approvals: list[ToolCallPart] = field(default_factory=list)
    """Tool calls that require human-in-the-loop approval."""

calls 类属性 实例属性

calls: list[ToolCallPart] = field(default_factory=list)

需要外部执行的工具调用。

approvals 类属性 实例属性

approvals: list[ToolCallPart] = field(default_factory=list)

需要人在回路中批准的工具调用。

ToolApproved 数据类

表示一个工具调用已被批准,并且应该执行该工具函数。

源代码位于 pydantic_ai_slim/pydantic_ai/tools.py
152
153
154
155
156
157
158
159
@dataclass(kw_only=True)
class ToolApproved:
    """Indicates that a tool call has been approved and that the tool function should be executed."""

    override_args: dict[str, Any] | None = None
    """Optional tool call arguments to use instead of the original arguments."""

    kind: Literal['tool-approved'] = 'tool-approved'

override_args 类属性 实例属性

override_args: dict[str, Any] | None = None

可选的工具调用参数,用于替代原始参数。

ToolDenied 数据类

表示一个工具调用已被拒绝,并且应向模型返回一条拒绝消息。

源代码位于 pydantic_ai_slim/pydantic_ai/tools.py
162
163
164
165
166
167
168
169
170
171
@dataclass
class ToolDenied:
    """Indicates that a tool call has been denied and that a denial message should be returned to the model."""

    message: str = 'The tool call was denied.'
    """The message to return to the model."""

    _: KW_ONLY

    kind: Literal['tool-denied'] = 'tool-denied'

message 类属性 实例属性

message: str = 'The tool call was denied.'

要返回给模型的消息。

DeferredToolResults 数据类

上一次运行中需要批准或外部执行的延迟工具调用的结果。

工具调用 ID 需要与上一次运行的 DeferredToolRequests 输出对象中的 ID 相匹配。

更多信息请参见延迟工具文档

源代码位于 pydantic_ai_slim/pydantic_ai/tools.py
201
202
203
204
205
206
207
208
209
210
211
212
213
@dataclass(kw_only=True)
class DeferredToolResults:
    """Results for deferred tool calls from a previous run that required approval or external execution.

    The tool call IDs need to match those from the [`DeferredToolRequests`][pydantic_ai.output.DeferredToolRequests] output object from the previous run.

    See [deferred tools docs](../deferred-tools.md#deferred-tools) for more information.
    """

    calls: dict[str, DeferredToolCallResult | Any] = field(default_factory=dict)
    """Map of tool call IDs to results for tool calls that required external execution."""
    approvals: dict[str, bool | DeferredToolApprovalResult] = field(default_factory=dict)
    """Map of tool call IDs to results for tool calls that required human-in-the-loop approval."""

calls 类属性 实例属性

calls: dict[str, DeferredToolCallResult | Any] = field(
    default_factory=dict
)

工具调用 ID 到需要外部执行的工具调用结果的映射。

approvals 类属性 实例属性

approvals: dict[str, bool | DeferredToolApprovalResult] = (
    field(default_factory=dict)
)

工具调用 ID 到需要人在回路中批准的工具调用结果的映射。

Tool 数据类

基类:Generic[AgentDepsT]

代理的工具函数。

源代码位于 pydantic_ai_slim/pydantic_ai/tools.py
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
@dataclass(init=False)
class Tool(Generic[AgentDepsT]):
    """A tool function for an agent."""

    function: ToolFuncEither[AgentDepsT]
    takes_ctx: bool
    max_retries: int | None
    name: str
    description: str | None
    prepare: ToolPrepareFunc[AgentDepsT] | None
    docstring_format: DocstringFormat
    require_parameter_descriptions: bool
    strict: bool | None
    requires_approval: bool
    function_schema: _function_schema.FunctionSchema
    """
    The base JSON schema for the tool's parameters.

    This schema may be modified by the `prepare` function or by the Model class prior to including it in an API request.
    """

    def __init__(
        self,
        function: ToolFuncEither[AgentDepsT],
        *,
        takes_ctx: bool | None = None,
        max_retries: int | None = None,
        name: str | None = None,
        description: str | None = None,
        prepare: ToolPrepareFunc[AgentDepsT] | None = None,
        docstring_format: DocstringFormat = 'auto',
        require_parameter_descriptions: bool = False,
        schema_generator: type[GenerateJsonSchema] = GenerateToolJsonSchema,
        strict: bool | None = None,
        requires_approval: bool = False,
        function_schema: _function_schema.FunctionSchema | None = None,
    ):
        """Create a new tool instance.

        Example usage:

        ```python {noqa="I001"}
        from pydantic_ai import Agent, RunContext, Tool

        async def my_tool(ctx: RunContext[int], x: int, y: int) -> str:
            return f'{ctx.deps} {x} {y}'

        agent = Agent('test', tools=[Tool(my_tool)])
        ```

        or with a custom prepare method:

        ```python {noqa="I001"}

        from pydantic_ai import Agent, RunContext, Tool
        from pydantic_ai.tools import ToolDefinition

        async def my_tool(ctx: RunContext[int], x: int, y: int) -> str:
            return f'{ctx.deps} {x} {y}'

        async def prep_my_tool(
            ctx: RunContext[int], tool_def: ToolDefinition
        ) -> ToolDefinition | None:
            # only register the tool if `deps == 42`
            if ctx.deps == 42:
                return tool_def

        agent = Agent('test', tools=[Tool(my_tool, prepare=prep_my_tool)])
        ```


        Args:
            function: The Python function to call as the tool.
            takes_ctx: Whether the function takes a [`RunContext`][pydantic_ai.tools.RunContext] first argument,
                this is inferred if unset.
            max_retries: Maximum number of retries allowed for this tool, set to the agent default if `None`.
            name: Name of the tool, inferred from the function if `None`.
            description: Description of the tool, inferred from the function if `None`.
            prepare: custom method to prepare the tool definition for each step, return `None` to omit this
                tool from a given step. This is useful if you want to customise a tool at call time,
                or omit it completely from a step. See [`ToolPrepareFunc`][pydantic_ai.tools.ToolPrepareFunc].
            docstring_format: The format of the docstring, see [`DocstringFormat`][pydantic_ai.tools.DocstringFormat].
                Defaults to `'auto'`, such that the format is inferred from the structure of the docstring.
            require_parameter_descriptions: If True, raise an error if a parameter description is missing. Defaults to False.
            schema_generator: The JSON schema generator class to use. Defaults to `GenerateToolJsonSchema`.
            strict: Whether to enforce JSON schema compliance (only affects OpenAI).
                See [`ToolDefinition`][pydantic_ai.tools.ToolDefinition] for more info.
            requires_approval: Whether this tool requires human-in-the-loop approval. Defaults to False.
                See the [tools documentation](../deferred-tools.md#human-in-the-loop-tool-approval) for more info.
            function_schema: The function schema to use for the tool. If not provided, it will be generated.
        """
        self.function = function
        self.function_schema = function_schema or _function_schema.function_schema(
            function,
            schema_generator,
            takes_ctx=takes_ctx,
            docstring_format=docstring_format,
            require_parameter_descriptions=require_parameter_descriptions,
        )
        self.takes_ctx = self.function_schema.takes_ctx
        self.max_retries = max_retries
        self.name = name or function.__name__
        self.description = description or self.function_schema.description
        self.prepare = prepare
        self.docstring_format = docstring_format
        self.require_parameter_descriptions = require_parameter_descriptions
        self.strict = strict
        self.requires_approval = requires_approval

    @classmethod
    def from_schema(
        cls,
        function: Callable[..., Any],
        name: str,
        description: str | None,
        json_schema: JsonSchemaValue,
        takes_ctx: bool = False,
    ) -> Self:
        """Creates a Pydantic tool from a function and a JSON schema.

        Args:
            function: The function to call.
                This will be called with keywords only, and no validation of
                the arguments will be performed.
            name: The unique name of the tool that clearly communicates its purpose
            description: Used to tell the model how/when/why to use the tool.
                You can provide few-shot examples as a part of the description.
            json_schema: The schema for the function arguments
            takes_ctx: An optional boolean parameter indicating whether the function
                accepts the context object as an argument.

        Returns:
            A Pydantic tool that calls the function
        """
        function_schema = _function_schema.FunctionSchema(
            function=function,
            description=description,
            validator=SchemaValidator(schema=core_schema.any_schema()),
            json_schema=json_schema,
            takes_ctx=takes_ctx,
            is_async=_utils.is_async_callable(function),
        )

        return cls(
            function,
            takes_ctx=takes_ctx,
            name=name,
            description=description,
            function_schema=function_schema,
        )

    @property
    def tool_def(self):
        return ToolDefinition(
            name=self.name,
            description=self.description,
            parameters_json_schema=self.function_schema.json_schema,
            strict=self.strict,
        )

    async def prepare_tool_def(self, ctx: RunContext[AgentDepsT]) -> ToolDefinition | None:
        """Get the tool definition.

        By default, this method creates a tool definition, then either returns it, or calls `self.prepare`
        if it's set.

        Returns:
            return a `ToolDefinition` or `None` if the tools should not be registered for this run.
        """
        base_tool_def = self.tool_def

        if self.requires_approval and not ctx.tool_call_approved:
            base_tool_def = replace(base_tool_def, kind='unapproved')

        if self.prepare is not None:
            return await self.prepare(ctx, base_tool_def)
        else:
            return base_tool_def

__init__

__init__(
    function: ToolFuncEither[AgentDepsT],
    *,
    takes_ctx: bool | None = None,
    max_retries: int | None = None,
    name: str | None = None,
    description: str | None = None,
    prepare: ToolPrepareFunc[AgentDepsT] | None = None,
    docstring_format: DocstringFormat = "auto",
    require_parameter_descriptions: bool = False,
    schema_generator: type[
        GenerateJsonSchema
    ] = GenerateToolJsonSchema,
    strict: bool | None = None,
    requires_approval: bool = False,
    function_schema: FunctionSchema | None = None
)

创建一个新的工具实例。

用法示例

from pydantic_ai import Agent, RunContext, Tool

async def my_tool(ctx: RunContext[int], x: int, y: int) -> str:
    return f'{ctx.deps} {x} {y}'

agent = Agent('test', tools=[Tool(my_tool)])

或使用自定义的 prepare 方法

from pydantic_ai import Agent, RunContext, Tool
from pydantic_ai.tools import ToolDefinition

async def my_tool(ctx: RunContext[int], x: int, y: int) -> str:
    return f'{ctx.deps} {x} {y}'

async def prep_my_tool(
    ctx: RunContext[int], tool_def: ToolDefinition
) -> ToolDefinition | None:
    # only register the tool if `deps == 42`
    if ctx.deps == 42:
        return tool_def

agent = Agent('test', tools=[Tool(my_tool, prepare=prep_my_tool)])

参数

名称 类型 描述 默认值
function ToolFuncEither[AgentDepsT]

作为工具调用的 Python 函数。

必需
takes_ctx bool | None

函数是否接受 RunContext 作为第一个参数,如果未设置,则会进行推断。

None
max_retries int | None

此工具允许的最大重试次数,如果为 None,则设置为代理的默认值。

None
name str | None

工具的名称,如果为 None,则从函数推断。

None
description str | None

工具的描述,如果为 None,则从函数推断。

None
prepare ToolPrepareFunc[AgentDepsT] | None

用于为每个步骤准备工具定义的自定义方法,返回 None 以从给定步骤中省略此工具。如果您想在调用时自定义工具,或从某个步骤中完全省略它,这将非常有用。请参见 ToolPrepareFunc

None
docstring_format DocstringFormat

文档字符串的格式,请参见 DocstringFormat。默认为 'auto',这样格式会从文档字符串的结构中推断出来。

'auto'
require_parameter_descriptions bool

如果为 True,则在缺少参数描述时引发错误。默认为 False。

False
schema_generator type[GenerateJsonSchema]

要使用的 JSON schema 生成器类。默认为 GenerateToolJsonSchema

GenerateToolJsonSchema
strict bool | None

是否强制执行 JSON schema 合规性(仅影响 OpenAI)。更多信息请参见 ToolDefinition

None
requires_approval bool

此工具是否需要人在回路中批准。默认为 False。更多信息请参见工具文档

False
function_schema FunctionSchema | None

用于工具的函数 schema。如果未提供,则会自动生成。

None
源代码位于 pydantic_ai_slim/pydantic_ai/tools.py
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
def __init__(
    self,
    function: ToolFuncEither[AgentDepsT],
    *,
    takes_ctx: bool | None = None,
    max_retries: int | None = None,
    name: str | None = None,
    description: str | None = None,
    prepare: ToolPrepareFunc[AgentDepsT] | None = None,
    docstring_format: DocstringFormat = 'auto',
    require_parameter_descriptions: bool = False,
    schema_generator: type[GenerateJsonSchema] = GenerateToolJsonSchema,
    strict: bool | None = None,
    requires_approval: bool = False,
    function_schema: _function_schema.FunctionSchema | None = None,
):
    """Create a new tool instance.

    Example usage:

    ```python {noqa="I001"}
    from pydantic_ai import Agent, RunContext, Tool

    async def my_tool(ctx: RunContext[int], x: int, y: int) -> str:
        return f'{ctx.deps} {x} {y}'

    agent = Agent('test', tools=[Tool(my_tool)])
    ```

    or with a custom prepare method:

    ```python {noqa="I001"}

    from pydantic_ai import Agent, RunContext, Tool
    from pydantic_ai.tools import ToolDefinition

    async def my_tool(ctx: RunContext[int], x: int, y: int) -> str:
        return f'{ctx.deps} {x} {y}'

    async def prep_my_tool(
        ctx: RunContext[int], tool_def: ToolDefinition
    ) -> ToolDefinition | None:
        # only register the tool if `deps == 42`
        if ctx.deps == 42:
            return tool_def

    agent = Agent('test', tools=[Tool(my_tool, prepare=prep_my_tool)])
    ```


    Args:
        function: The Python function to call as the tool.
        takes_ctx: Whether the function takes a [`RunContext`][pydantic_ai.tools.RunContext] first argument,
            this is inferred if unset.
        max_retries: Maximum number of retries allowed for this tool, set to the agent default if `None`.
        name: Name of the tool, inferred from the function if `None`.
        description: Description of the tool, inferred from the function if `None`.
        prepare: custom method to prepare the tool definition for each step, return `None` to omit this
            tool from a given step. This is useful if you want to customise a tool at call time,
            or omit it completely from a step. See [`ToolPrepareFunc`][pydantic_ai.tools.ToolPrepareFunc].
        docstring_format: The format of the docstring, see [`DocstringFormat`][pydantic_ai.tools.DocstringFormat].
            Defaults to `'auto'`, such that the format is inferred from the structure of the docstring.
        require_parameter_descriptions: If True, raise an error if a parameter description is missing. Defaults to False.
        schema_generator: The JSON schema generator class to use. Defaults to `GenerateToolJsonSchema`.
        strict: Whether to enforce JSON schema compliance (only affects OpenAI).
            See [`ToolDefinition`][pydantic_ai.tools.ToolDefinition] for more info.
        requires_approval: Whether this tool requires human-in-the-loop approval. Defaults to False.
            See the [tools documentation](../deferred-tools.md#human-in-the-loop-tool-approval) for more info.
        function_schema: The function schema to use for the tool. If not provided, it will be generated.
    """
    self.function = function
    self.function_schema = function_schema or _function_schema.function_schema(
        function,
        schema_generator,
        takes_ctx=takes_ctx,
        docstring_format=docstring_format,
        require_parameter_descriptions=require_parameter_descriptions,
    )
    self.takes_ctx = self.function_schema.takes_ctx
    self.max_retries = max_retries
    self.name = name or function.__name__
    self.description = description or self.function_schema.description
    self.prepare = prepare
    self.docstring_format = docstring_format
    self.require_parameter_descriptions = require_parameter_descriptions
    self.strict = strict
    self.requires_approval = requires_approval

function_schema 实例属性

function_schema: FunctionSchema = (
    function_schema
    or function_schema(
        function,
        schema_generator,
        takes_ctx=takes_ctx,
        docstring_format=docstring_format,
        require_parameter_descriptions=require_parameter_descriptions,
    )
)

工具参数的基础 JSON schema。

此 schema 可能会被 prepare 函数或 Model 类在将其包含在 API 请求之前进行修改。

from_schema 类方法

from_schema(
    function: Callable[..., Any],
    name: str,
    description: str | None,
    json_schema: JsonSchemaValue,
    takes_ctx: bool = False,
) -> Self

从一个函数和一个 JSON schema 创建一个 Pydantic 工具。

参数

名称 类型 描述 默认值
function Callable[..., Any]

要调用的函数。将仅使用关键字参数调用此函数,并且不会对参数进行验证。

必需
name str

工具的唯一名称,清楚地传达其目的

必需
description str | None

用于告诉模型如何/何时/为什么使用该工具。您可以提供少量示例作为描述的一部分。

必需
json_schema JsonSchemaValue

函数参数的 schema

必需
takes_ctx bool

一个可选的布尔参数,指示函数是否接受上下文对象作为参数。

False

返回

类型 描述
Self

一个调用该函数的 Pydantic 工具

源代码位于 pydantic_ai_slim/pydantic_ai/tools.py
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
@classmethod
def from_schema(
    cls,
    function: Callable[..., Any],
    name: str,
    description: str | None,
    json_schema: JsonSchemaValue,
    takes_ctx: bool = False,
) -> Self:
    """Creates a Pydantic tool from a function and a JSON schema.

    Args:
        function: The function to call.
            This will be called with keywords only, and no validation of
            the arguments will be performed.
        name: The unique name of the tool that clearly communicates its purpose
        description: Used to tell the model how/when/why to use the tool.
            You can provide few-shot examples as a part of the description.
        json_schema: The schema for the function arguments
        takes_ctx: An optional boolean parameter indicating whether the function
            accepts the context object as an argument.

    Returns:
        A Pydantic tool that calls the function
    """
    function_schema = _function_schema.FunctionSchema(
        function=function,
        description=description,
        validator=SchemaValidator(schema=core_schema.any_schema()),
        json_schema=json_schema,
        takes_ctx=takes_ctx,
        is_async=_utils.is_async_callable(function),
    )

    return cls(
        function,
        takes_ctx=takes_ctx,
        name=name,
        description=description,
        function_schema=function_schema,
    )

prepare_tool_def 异步

prepare_tool_def(
    ctx: RunContext[AgentDepsT],
) -> ToolDefinition | None

获取工具定义。

默认情况下,此方法创建一个工具定义,然后返回它,或者如果设置了 self.prepare,则调用它。

返回

类型 描述
ToolDefinition | None

如果工具不应为此运行注册,则返回一个 ToolDefinitionNone

源代码位于 pydantic_ai_slim/pydantic_ai/tools.py
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
async def prepare_tool_def(self, ctx: RunContext[AgentDepsT]) -> ToolDefinition | None:
    """Get the tool definition.

    By default, this method creates a tool definition, then either returns it, or calls `self.prepare`
    if it's set.

    Returns:
        return a `ToolDefinition` or `None` if the tools should not be registered for this run.
    """
    base_tool_def = self.tool_def

    if self.requires_approval and not ctx.tool_call_approved:
        base_tool_def = replace(base_tool_def, kind='unapproved')

    if self.prepare is not None:
        return await self.prepare(ctx, base_tool_def)
    else:
        return base_tool_def

ObjectJsonSchema 模块属性

ObjectJsonSchema: TypeAlias = dict[str, Any]

表示对象 JSON schema 的类型,例如其中 "type": "object"

此类型用于在 ToolDefinition 中定义工具参数(即参数)。

根据 PEP-728,这应该是一个带有 type: Literal['object']extra_parts=Any 的 TypedDict。

ToolDefinition 数据类

传递给模型的工具的定义。

这用于函数工具和输出工具。

源代码位于 pydantic_ai_slim/pydantic_ai/tools.py
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
@dataclass(repr=False, kw_only=True)
class ToolDefinition:
    """Definition of a tool passed to a model.

    This is used for both function tools and output tools.
    """

    name: str
    """The name of the tool."""

    parameters_json_schema: ObjectJsonSchema = field(default_factory=lambda: {'type': 'object', 'properties': {}})
    """The JSON schema for the tool's parameters."""

    description: str | None = None
    """The description of the tool."""

    outer_typed_dict_key: str | None = None
    """The key in the outer [TypedDict] that wraps an output tool.

    This will only be set for output tools which don't have an `object` JSON schema.
    """

    strict: bool | None = None
    """Whether to enforce (vendor-specific) strict JSON schema validation for tool calls.

    Setting this to `True` while using a supported model generally imposes some restrictions on the tool's JSON schema
    in exchange for guaranteeing the API responses strictly match that schema.

    When `False`, the model may be free to generate other properties or types (depending on the vendor).
    When `None` (the default), the value will be inferred based on the compatibility of the parameters_json_schema.

    Note: this is currently only supported by OpenAI models.
    """

    kind: ToolKind = field(default='function')
    """The kind of tool:

    - `'function'`: a tool that will be executed by Pydantic AI during an agent run and has its result returned to the model
    - `'output'`: a tool that passes through an output value that ends the run
    - `'external'`: a tool whose result will be produced outside of the Pydantic AI agent run in which it was called, because it depends on an upstream service (or user) or could take longer to generate than it's reasonable to keep the agent process running.
        See the [tools documentation](../deferred-tools.md#deferred-tools) for more info.
    - `'unapproved'`: a tool that requires human-in-the-loop approval.
        See the [tools documentation](../deferred-tools.md#human-in-the-loop-tool-approval) for more info.
    """

    @property
    def defer(self) -> bool:
        """Whether calls to this tool will be deferred.

        See the [tools documentation](../deferred-tools.md#deferred-tools) for more info.
        """
        return self.kind in ('external', 'unapproved')

    __repr__ = _utils.dataclasses_no_defaults_repr

name instance-attribute

name: str

工具的名称。

parameters_json_schema 类属性 实例属性

parameters_json_schema: ObjectJsonSchema = field(
    default_factory=lambda: {
        "type": "object",
        "properties": {},
    }
)

工具参数的 JSON schema。

description 类属性 实例属性

description: str | None = None

工具的描述。

outer_typed_dict_key 类属性 实例属性

outer_typed_dict_key: str | None = None

包装输出工具的外部 [TypedDict] 中的键。

这仅对没有 object JSON schema 的输出工具设置。

strict 类属性 实例属性

strict: bool | None = None

是否对工具调用强制执行(供应商特定的)严格 JSON schema 验证。

在使用支持的模型时将此设置为 True 通常会对工具的 JSON schema 施加一些限制,以换取保证 API 响应严格匹配该 schema。

当为 False 时,模型可以自由生成其他属性或类型(取决于供应商)。当为 None(默认值)时,将根据 parameters_json_schema 的兼容性推断该值。

注意:这目前仅由 OpenAI 模型支持。

kind 类属性 实例属性

kind: ToolKind = field(default='function')

工具的类型

  • 'function':在代理运行期间由 Pydantic AI 执行并将其结果返回给模型的工具
  • 'output':传递一个结束运行的输出值的工具
  • 'external':其结果将在调用它的 Pydantic AI 代理运行之外生成的工具,因为它依赖于上游服务(或用户),或者生成时间可能比保持代理进程运行的合理时间更长。更多信息请参见工具文档
  • 'unapproved':需要人在回路中批准的工具。更多信息请参见工具文档

defer 属性

defer: bool

对此工具的调用是否将被推迟。

更多信息请参见工具文档