Skip to content

pydantic_ai.function_signature

Generate function signatures from functions and JSON schemas.

This module provides utilities to represent tool definitions as human-readable function signatures, which LLMs can understand more easily than raw JSON schemas. Used by code mode to present tools as callable functions.

SimpleTypeExpr dataclass

A simple named type like str, int, Any, None.

Source code in pydantic_ai_slim/pydantic_ai/function_signature.py
41
42
43
44
45
46
47
48
49
@dataclass
class SimpleTypeExpr:
    """A simple named type like `str`, `int`, `Any`, `None`."""

    name: SimpleTypeName
    kind: Literal['simple'] = 'simple'

    def __str__(self) -> str:
        return self.name

LiteralTypeExpr dataclass

A Literal type expression like Literal['a', 'b'] or Literal[42].

Source code in pydantic_ai_slim/pydantic_ai/function_signature.py
52
53
54
55
56
57
58
59
60
@dataclass
class LiteralTypeExpr:
    """A Literal type expression like `Literal['a', 'b']` or `Literal[42]`."""

    values: list[Any]
    kind: Literal['literal'] = 'literal'

    def __str__(self) -> str:
        return f'Literal[{", ".join(repr(v) for v in self.values)}]'

GenericTypeExpr dataclass

A generic type expression like list[User], dict[str, User], tuple[int, str].

Source code in pydantic_ai_slim/pydantic_ai/function_signature.py
63
64
65
66
67
68
69
70
71
72
@dataclass
class GenericTypeExpr:
    """A generic type expression like `list[User]`, `dict[str, User]`, `tuple[int, str]`."""

    base: str
    args: list[TypeExpr]
    kind: Literal['generic'] = 'generic'

    def __str__(self) -> str:
        return f'{self.base}[{", ".join(str(a) for a in self.args)}]'

UnionTypeExpr dataclass

A union type expression like User | None, str | int.

Source code in pydantic_ai_slim/pydantic_ai/function_signature.py
75
76
77
78
79
80
81
82
83
@dataclass
class UnionTypeExpr:
    """A union type expression like `User | None`, `str | int`."""

    members: list[TypeExpr]
    kind: Literal['union'] = 'union'

    def __str__(self) -> str:
        return ' | '.join(str(m) for m in self.members)

TypeExpr module-attribute

TypeExpr: TypeAlias = (
    "TypeSignature | SimpleTypeExpr | LiteralTypeExpr | GenericTypeExpr | UnionTypeExpr"
)

A type expression node in the signature's type tree.

TypeFieldSignature dataclass

A single field in a TypedDict-style type definition.

Source code in pydantic_ai_slim/pydantic_ai/function_signature.py
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
@dataclass(kw_only=True)
class TypeFieldSignature:
    """A single field in a TypedDict-style type definition."""

    name: str
    type: TypeExpr
    required: bool = False
    description: str | None = None
    kind: Literal['field'] = 'field'

    def __str__(self) -> str:
        """Render this field as a line in a TypedDict class body."""
        type_str = str(self.type)
        if not self.required:
            type_str = f'NotRequired[{type_str}]'
        lines: list[str] = [f'    {self.name}: {type_str}']
        if self.description:
            lines.extend(_render_description(self.description, indent='    '))
        return '\n'.join(lines)

__str__

__str__() -> str

Render this field as a line in a TypedDict class body.

Source code in pydantic_ai_slim/pydantic_ai/function_signature.py
117
118
119
120
121
122
123
124
125
def __str__(self) -> str:
    """Render this field as a line in a TypedDict class body."""
    type_str = str(self.type)
    if not self.required:
        type_str = f'NotRequired[{type_str}]'
    lines: list[str] = [f'    {self.name}: {type_str}']
    if self.description:
        lines.extend(_render_description(self.description, indent='    '))
    return '\n'.join(lines)

TypeSignature dataclass

A TypedDict-style class definition with named fields.

Source code in pydantic_ai_slim/pydantic_ai/function_signature.py
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
@dataclass(kw_only=True)
class TypeSignature:
    """A TypedDict-style class definition with named fields."""

    name: str

    description: str | None = None

    fields: dict[str, TypeFieldSignature] = field(default_factory=dict[str, TypeFieldSignature])
    kind: Literal['type'] = 'type'

    @property
    def display_name(self) -> str:
        """The type name, with tool-name prefix applied if rendering context is set."""
        return _type_name_overrides.get().get(self.name, self.name)

    def __str__(self) -> str:
        """Return the type name (for use in type expressions like `def foo(x: User)`)."""
        return self.display_name

    def render_definition(
        self, *, owner_name: str | None = None, conflicting_type_names: frozenset[str] = frozenset()
    ) -> str:
        """Render the full TypedDict class definition.

        Args:
            owner_name: The owning tool name, used to build prefixed type names
                for conflicting types (e.g. `get_user_Address`).
            conflicting_type_names: Set of type names that need tool-name prefixes
                (from `get_conflicting_type_names`). Only effective when `owner_name`
                is also provided.
        """
        if owner_name and conflicting_type_names:
            overrides = {n: f'{owner_name}_{n}' for n in conflicting_type_names}
            token = _type_name_overrides.set(overrides)
            try:
                return self._render_definition()
            finally:
                _type_name_overrides.reset(token)
        return self._render_definition()

    def _render_definition(self) -> str:
        """Render the full TypedDict class definition (internal, assumes overrides are set)."""
        lines = [f'class {self.display_name}(TypedDict):']
        if self.description:
            lines.extend(_render_description(self.description, indent='    '))
        if not self.fields:
            if not self.description:
                lines.append('    pass')
        else:
            for f in self.fields.values():
                lines.append(str(f))
        return '\n'.join(lines)

    def structurally_equal(self, other: TypeSignature) -> bool:
        """Compare two TypeSignatures structurally, ignoring descriptions."""
        if set(self.fields.keys()) != set(other.fields.keys()):
            return False
        for name, f in self.fields.items():
            other_f = other.fields[name]
            if f.required != other_f.required:
                return False
            if str(f.type) != str(other_f.type):
                return False
        return True

display_name property

display_name: str

The type name, with tool-name prefix applied if rendering context is set.

__str__

__str__() -> str

Return the type name (for use in type expressions like def foo(x: User)).

Source code in pydantic_ai_slim/pydantic_ai/function_signature.py
144
145
146
def __str__(self) -> str:
    """Return the type name (for use in type expressions like `def foo(x: User)`)."""
    return self.display_name

render_definition

render_definition(
    *,
    owner_name: str | None = None,
    conflicting_type_names: frozenset[str] = frozenset()
) -> str

Render the full TypedDict class definition.

Parameters:

Name Type Description Default
owner_name str | None

The owning tool name, used to build prefixed type names for conflicting types (e.g. get_user_Address).

None
conflicting_type_names frozenset[str]

Set of type names that need tool-name prefixes (from get_conflicting_type_names). Only effective when owner_name is also provided.

frozenset()
Source code in pydantic_ai_slim/pydantic_ai/function_signature.py
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
def render_definition(
    self, *, owner_name: str | None = None, conflicting_type_names: frozenset[str] = frozenset()
) -> str:
    """Render the full TypedDict class definition.

    Args:
        owner_name: The owning tool name, used to build prefixed type names
            for conflicting types (e.g. `get_user_Address`).
        conflicting_type_names: Set of type names that need tool-name prefixes
            (from `get_conflicting_type_names`). Only effective when `owner_name`
            is also provided.
    """
    if owner_name and conflicting_type_names:
        overrides = {n: f'{owner_name}_{n}' for n in conflicting_type_names}
        token = _type_name_overrides.set(overrides)
        try:
            return self._render_definition()
        finally:
            _type_name_overrides.reset(token)
    return self._render_definition()

structurally_equal

structurally_equal(other: TypeSignature) -> bool

Compare two TypeSignatures structurally, ignoring descriptions.

Source code in pydantic_ai_slim/pydantic_ai/function_signature.py
182
183
184
185
186
187
188
189
190
191
192
def structurally_equal(self, other: TypeSignature) -> bool:
    """Compare two TypeSignatures structurally, ignoring descriptions."""
    if set(self.fields.keys()) != set(other.fields.keys()):
        return False
    for name, f in self.fields.items():
        other_f = other.fields[name]
        if f.required != other_f.required:
            return False
        if str(f.type) != str(other_f.type):
            return False
    return True

FunctionParam dataclass

A single parameter in a function signature.

Source code in pydantic_ai_slim/pydantic_ai/function_signature.py
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
@dataclass(kw_only=True)
class FunctionParam:
    """A single parameter in a function signature."""

    name: str
    type: TypeExpr
    default: str | None = None
    kind: Literal['param'] = 'param'

    def __str__(self) -> str:
        """Render this parameter as a function parameter string."""
        type_str = str(self.type)
        if self.default is not None:
            return f'{self.name}: {type_str} = {self.default}'
        return f'{self.name}: {type_str}'

__str__

__str__() -> str

Render this parameter as a function parameter string.

Source code in pydantic_ai_slim/pydantic_ai/function_signature.py
204
205
206
207
208
209
def __str__(self) -> str:
    """Render this parameter as a function parameter string."""
    type_str = str(self.type)
    if self.default is not None:
        return f'{self.name}: {type_str} = {self.default}'
    return f'{self.name}: {type_str}'

FunctionSignature dataclass

Function signature shape with referenced type definitions.

This class holds the structural data (params, return type, referenced types) needed to render a function signature. Name and description can be overridden at render time (e.g. from a ToolDefinition).

Source code in pydantic_ai_slim/pydantic_ai/function_signature.py
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
@dataclass(kw_only=True)
class FunctionSignature:
    """Function signature shape with referenced type definitions.

    This class holds the structural data (params, return type, referenced types)
    needed to render a function signature. Name and description can be overridden
    at render time (e.g. from a `ToolDefinition`).
    """

    name: str
    description: str | None = None

    params: dict[str, FunctionParam] = field(default_factory=dict[str, FunctionParam])
    """Function parameters, all rendered as keyword-only (JSON schema doesn't distinguish positional/keyword)."""

    return_type: TypeExpr
    """The return type expression."""

    referenced_types: list[TypeSignature] = field(default_factory=list[TypeSignature])
    """TypedDict class definitions needed by the signature."""

    is_async: bool = False
    """Whether the underlying function is async."""

    kind: Literal['function'] = 'function'

    def render(
        self,
        body: str,
        *,
        name: str | None = None,
        description: str | None = None,
        is_async: bool | None = None,
        conflicting_type_names: frozenset[str] = frozenset(),
    ) -> str:
        """Render the signature with a specific body.

        Sets `_type_name_overrides` so that dedup-prefixed types resolve
        correctly during rendering.

        Args:
            body: The function body (e.g. `'...'` or `'return await tool()'`).
            name: The function name (also used for dedup prefix resolution). Falls back to `self.name`.
            description: Optional docstring to include. Falls back to `self.description`.
            is_async: Override async rendering. If `None`, uses `self.is_async`.
            conflicting_type_names: Set of type names that need tool-name prefixes (from `get_conflicting_type_names`).
        """
        render_name = name or self.name
        description = description if description is not None else self.description
        overrides = {n: f'{render_name}_{n}' for n in conflicting_type_names}
        token = _type_name_overrides.set(overrides)
        try:
            return self._render(body, name=render_name, description=description, is_async=is_async)
        finally:
            _type_name_overrides.reset(token)

    def _render(
        self,
        body: str,
        *,
        name: str,
        description: str | None = None,
        is_async: bool | None = None,
    ) -> str:
        async_flag = is_async if is_async is not None else self.is_async
        prefix = 'async def' if async_flag else 'def'
        params_str = ', '.join(str(p) for p in self.params.values())

        return_str = str(self.return_type)
        if params_str:
            # Force keyword-only params so LLMs always use named arguments
            parts = [f'{prefix} {name}(*, {params_str}) -> {return_str}:']
        else:
            parts = [f'{prefix} {name}() -> {return_str}:']

        if description:
            parts.extend(_render_description(description, indent='    '))

        parts.append(f'    {body}')

        return '\n'.join(parts)

    @classmethod
    def from_schema(
        cls,
        *,
        name: str,
        parameters_schema: dict[str, Any],
        return_schema: dict[str, Any] | None = None,
    ) -> FunctionSignature:
        """Build a FunctionSignature from JSON schemas.

        `name` is stored on the resulting signature and also used for generating
        fallback type names (e.g. `GetUserAddress`) when the schema has no `title`.

        Parameter and return schemas are processed independently — each resolves
        `$ref`s against its own `$defs`. Name collisions between parameter and return
        types (e.g. both define a `User` `$def` with different structures) are handled
        by `get_conflicting_type_names` at a later stage.
        """
        # Process parameter schema with its own $defs
        param_defs = parameters_schema.get('$defs', {})
        param_referenced: dict[str, TypeSignature] = {}
        _process_schema_defs(param_defs, param_referenced, name)
        params = _build_params_from_schema(parameters_schema, param_defs, param_referenced, name)

        # Process return schema independently (its own $defs)
        resolved_return_type: TypeExpr = _ANY
        return_referenced: dict[str, TypeSignature] = {}
        if return_schema is not None:
            return_defs = return_schema.get('$defs', {})
            _process_schema_defs(return_defs, return_referenced, name)
            resolved_return_type = _schema_to_type_expr(
                return_schema, return_defs, return_referenced, name, path='Return'
            )

        # Merge referenced types, deduplicating structurally identical types within this signature.
        # Cross-signature collisions are handled later by get_conflicting_type_names.
        all_referenced = list(param_referenced.values())
        for ret_type in return_referenced.values():
            existing = param_referenced.get(ret_type.name)
            if existing is not None and existing.structurally_equal(ret_type):
                continue  # already present from param schema
            all_referenced.append(ret_type)

        return cls(
            name=name,
            params=params,
            return_type=resolved_return_type,
            referenced_types=all_referenced,
        )

    @staticmethod
    def get_conflicting_type_names(signatures: list[FunctionSignature]) -> frozenset[str]:
        """Identify TypedDict name conflicts across multiple tool signatures.

        Each signature keeps all its referenced types (so it remains self-contained),
        but identical types (same name and structure) are unified to the same object
        instance.

        Returns the set of type names that have conflicts (same name, different
        structure) and need tool-name prefixes at render time. Pass this set to
        `FunctionSignature.render(conflicting_type_names=...)`.

        Use `collect_unique_referenced_types()` when rendering to emit each
        definition once.
        """
        seen: dict[str, TypeSignature] = {}
        prefixed: set[str] = set()

        for sig in signatures:
            deduped: list[TypeSignature] = []
            for type_sig in sig.referenced_types:
                name = type_sig.name
                if name not in seen:
                    seen[name] = type_sig
                    deduped.append(type_sig)
                elif seen[name].structurally_equal(type_sig):
                    canonical = seen[name]
                    _replace_type_refs(sig, type_sig, canonical)
                    deduped.append(canonical)
                else:
                    prefixed.add(name)
                    deduped.append(type_sig)
            sig.referenced_types = deduped

        return frozenset(prefixed)

    @staticmethod
    def collect_unique_referenced_types(signatures: list[FunctionSignature]) -> list[TypeSignature]:
        """Collect unique TypeSignature objects from signatures, deduplicating by identity."""
        seen_ids: set[int] = set()
        result: list[TypeSignature] = []
        for sig in signatures:
            for type_sig in sig.referenced_types:
                if id(type_sig) not in seen_ids:
                    seen_ids.add(id(type_sig))
                    result.append(type_sig)
        return result

    @staticmethod
    def render_type_definitions(
        signatures: list[FunctionSignature],
        conflicting_type_names: frozenset[str],
    ) -> list[str]:
        """Render unique TypedDict definitions for a set of function signatures.

        For types whose names conflict across signatures (as identified by
        `get_conflicting_type_names`), each definition is rendered with a
        tool-name prefix (e.g. `get_user_Address`).

        Args:
            signatures: The function signatures (after `get_conflicting_type_names`).
            conflicting_type_names: The set returned by `get_conflicting_type_names`.

        Returns:
            A list of rendered TypedDict class definitions as strings.
        """
        unique_types = FunctionSignature.collect_unique_referenced_types(signatures)
        if not unique_types:
            return []

        owner_for: dict[int, str] = {}
        for sig in signatures:
            for tsig in sig.referenced_types:
                if tsig.name in conflicting_type_names and id(tsig) not in owner_for:
                    owner_for[id(tsig)] = sig.name

        rendered: list[str] = []
        for tsig in unique_types:
            owner = owner_for.get(id(tsig))
            rendered.append(tsig.render_definition(owner_name=owner, conflicting_type_names=conflicting_type_names))
        return rendered

params class-attribute instance-attribute

params: dict[str, FunctionParam] = field(
    default_factory=dict[str, FunctionParam]
)

Function parameters, all rendered as keyword-only (JSON schema doesn't distinguish positional/keyword).

return_type instance-attribute

return_type: TypeExpr

The return type expression.

referenced_types class-attribute instance-attribute

referenced_types: list[TypeSignature] = field(
    default_factory=list[TypeSignature]
)

TypedDict class definitions needed by the signature.

is_async class-attribute instance-attribute

is_async: bool = False

Whether the underlying function is async.

render

render(
    body: str,
    *,
    name: str | None = None,
    description: str | None = None,
    is_async: bool | None = None,
    conflicting_type_names: frozenset[str] = frozenset()
) -> str

Render the signature with a specific body.

Sets _type_name_overrides so that dedup-prefixed types resolve correctly during rendering.

Parameters:

Name Type Description Default
body str

The function body (e.g. '...' or 'return await tool()').

required
name str | None

The function name (also used for dedup prefix resolution). Falls back to self.name.

None
description str | None

Optional docstring to include. Falls back to self.description.

None
is_async bool | None

Override async rendering. If None, uses self.is_async.

None
conflicting_type_names frozenset[str]

Set of type names that need tool-name prefixes (from get_conflicting_type_names).

frozenset()
Source code in pydantic_ai_slim/pydantic_ai/function_signature.py
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
def render(
    self,
    body: str,
    *,
    name: str | None = None,
    description: str | None = None,
    is_async: bool | None = None,
    conflicting_type_names: frozenset[str] = frozenset(),
) -> str:
    """Render the signature with a specific body.

    Sets `_type_name_overrides` so that dedup-prefixed types resolve
    correctly during rendering.

    Args:
        body: The function body (e.g. `'...'` or `'return await tool()'`).
        name: The function name (also used for dedup prefix resolution). Falls back to `self.name`.
        description: Optional docstring to include. Falls back to `self.description`.
        is_async: Override async rendering. If `None`, uses `self.is_async`.
        conflicting_type_names: Set of type names that need tool-name prefixes (from `get_conflicting_type_names`).
    """
    render_name = name or self.name
    description = description if description is not None else self.description
    overrides = {n: f'{render_name}_{n}' for n in conflicting_type_names}
    token = _type_name_overrides.set(overrides)
    try:
        return self._render(body, name=render_name, description=description, is_async=is_async)
    finally:
        _type_name_overrides.reset(token)

from_schema classmethod

from_schema(
    *,
    name: str,
    parameters_schema: dict[str, Any],
    return_schema: dict[str, Any] | None = None
) -> FunctionSignature

Build a FunctionSignature from JSON schemas.

name is stored on the resulting signature and also used for generating fallback type names (e.g. GetUserAddress) when the schema has no title.

Parameter and return schemas are processed independently — each resolves $refs against its own $defs. Name collisions between parameter and return types (e.g. both define a User $def with different structures) are handled by get_conflicting_type_names at a later stage.

Source code in pydantic_ai_slim/pydantic_ai/function_signature.py
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
@classmethod
def from_schema(
    cls,
    *,
    name: str,
    parameters_schema: dict[str, Any],
    return_schema: dict[str, Any] | None = None,
) -> FunctionSignature:
    """Build a FunctionSignature from JSON schemas.

    `name` is stored on the resulting signature and also used for generating
    fallback type names (e.g. `GetUserAddress`) when the schema has no `title`.

    Parameter and return schemas are processed independently — each resolves
    `$ref`s against its own `$defs`. Name collisions between parameter and return
    types (e.g. both define a `User` `$def` with different structures) are handled
    by `get_conflicting_type_names` at a later stage.
    """
    # Process parameter schema with its own $defs
    param_defs = parameters_schema.get('$defs', {})
    param_referenced: dict[str, TypeSignature] = {}
    _process_schema_defs(param_defs, param_referenced, name)
    params = _build_params_from_schema(parameters_schema, param_defs, param_referenced, name)

    # Process return schema independently (its own $defs)
    resolved_return_type: TypeExpr = _ANY
    return_referenced: dict[str, TypeSignature] = {}
    if return_schema is not None:
        return_defs = return_schema.get('$defs', {})
        _process_schema_defs(return_defs, return_referenced, name)
        resolved_return_type = _schema_to_type_expr(
            return_schema, return_defs, return_referenced, name, path='Return'
        )

    # Merge referenced types, deduplicating structurally identical types within this signature.
    # Cross-signature collisions are handled later by get_conflicting_type_names.
    all_referenced = list(param_referenced.values())
    for ret_type in return_referenced.values():
        existing = param_referenced.get(ret_type.name)
        if existing is not None and existing.structurally_equal(ret_type):
            continue  # already present from param schema
        all_referenced.append(ret_type)

    return cls(
        name=name,
        params=params,
        return_type=resolved_return_type,
        referenced_types=all_referenced,
    )

get_conflicting_type_names staticmethod

get_conflicting_type_names(
    signatures: list[FunctionSignature],
) -> frozenset[str]

Identify TypedDict name conflicts across multiple tool signatures.

Each signature keeps all its referenced types (so it remains self-contained), but identical types (same name and structure) are unified to the same object instance.

Returns the set of type names that have conflicts (same name, different structure) and need tool-name prefixes at render time. Pass this set to FunctionSignature.render(conflicting_type_names=...).

Use collect_unique_referenced_types() when rendering to emit each definition once.

Source code in pydantic_ai_slim/pydantic_ai/function_signature.py
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
@staticmethod
def get_conflicting_type_names(signatures: list[FunctionSignature]) -> frozenset[str]:
    """Identify TypedDict name conflicts across multiple tool signatures.

    Each signature keeps all its referenced types (so it remains self-contained),
    but identical types (same name and structure) are unified to the same object
    instance.

    Returns the set of type names that have conflicts (same name, different
    structure) and need tool-name prefixes at render time. Pass this set to
    `FunctionSignature.render(conflicting_type_names=...)`.

    Use `collect_unique_referenced_types()` when rendering to emit each
    definition once.
    """
    seen: dict[str, TypeSignature] = {}
    prefixed: set[str] = set()

    for sig in signatures:
        deduped: list[TypeSignature] = []
        for type_sig in sig.referenced_types:
            name = type_sig.name
            if name not in seen:
                seen[name] = type_sig
                deduped.append(type_sig)
            elif seen[name].structurally_equal(type_sig):
                canonical = seen[name]
                _replace_type_refs(sig, type_sig, canonical)
                deduped.append(canonical)
            else:
                prefixed.add(name)
                deduped.append(type_sig)
        sig.referenced_types = deduped

    return frozenset(prefixed)

collect_unique_referenced_types staticmethod

collect_unique_referenced_types(
    signatures: list[FunctionSignature],
) -> list[TypeSignature]

Collect unique TypeSignature objects from signatures, deduplicating by identity.

Source code in pydantic_ai_slim/pydantic_ai/function_signature.py
380
381
382
383
384
385
386
387
388
389
390
@staticmethod
def collect_unique_referenced_types(signatures: list[FunctionSignature]) -> list[TypeSignature]:
    """Collect unique TypeSignature objects from signatures, deduplicating by identity."""
    seen_ids: set[int] = set()
    result: list[TypeSignature] = []
    for sig in signatures:
        for type_sig in sig.referenced_types:
            if id(type_sig) not in seen_ids:
                seen_ids.add(id(type_sig))
                result.append(type_sig)
    return result

render_type_definitions staticmethod

render_type_definitions(
    signatures: list[FunctionSignature],
    conflicting_type_names: frozenset[str],
) -> list[str]

Render unique TypedDict definitions for a set of function signatures.

For types whose names conflict across signatures (as identified by get_conflicting_type_names), each definition is rendered with a tool-name prefix (e.g. get_user_Address).

Parameters:

Name Type Description Default
signatures list[FunctionSignature]

The function signatures (after get_conflicting_type_names).

required
conflicting_type_names frozenset[str]

The set returned by get_conflicting_type_names.

required

Returns:

Type Description
list[str]

A list of rendered TypedDict class definitions as strings.

Source code in pydantic_ai_slim/pydantic_ai/function_signature.py
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
@staticmethod
def render_type_definitions(
    signatures: list[FunctionSignature],
    conflicting_type_names: frozenset[str],
) -> list[str]:
    """Render unique TypedDict definitions for a set of function signatures.

    For types whose names conflict across signatures (as identified by
    `get_conflicting_type_names`), each definition is rendered with a
    tool-name prefix (e.g. `get_user_Address`).

    Args:
        signatures: The function signatures (after `get_conflicting_type_names`).
        conflicting_type_names: The set returned by `get_conflicting_type_names`.

    Returns:
        A list of rendered TypedDict class definitions as strings.
    """
    unique_types = FunctionSignature.collect_unique_referenced_types(signatures)
    if not unique_types:
        return []

    owner_for: dict[int, str] = {}
    for sig in signatures:
        for tsig in sig.referenced_types:
            if tsig.name in conflicting_type_names and id(tsig) not in owner_for:
                owner_for[id(tsig)] = sig.name

    rendered: list[str] = []
    for tsig in unique_types:
        owner = owner_for.get(id(tsig))
        rendered.append(tsig.render_definition(owner_name=owner, conflicting_type_names=conflicting_type_names))
    return rendered