Skip to content

SkillsToolset API Reference

Bases: FunctionToolset[Any]

Pydantic AI toolset for automatic skill discovery and integration.

See skills docs for more information.

This is the primary interface for integrating skills with Pydantic AI agents. It manages skills directly and provides tools for skill interaction.

Provides the following tools to agents: - list_skills(): List all available skills - load_skill(skill_name): Load a specific skill's instructions - read_skill_resource(skill_name, resource_name): Read a skill resource file - run_skill_script(skill_name, script_name, args): Execute a skill script

Example
from pydantic_ai import Agent, SkillsToolset

# Default: uses ./skills directory
agent = Agent(
    model='openai:gpt-5.2',
    instructions="You are a helpful assistant.",
    toolsets=[SkillsToolset()]
)

# Multiple directories
agent = Agent(
    model='openai:gpt-5.2',
    toolsets=[SkillsToolset(directories=["./skills", "./more-skills"])]
)

# Programmatic skills
from pydantic_ai.toolsets.skills import Skill, SkillMetadata

custom_skill = Skill(
    name="my-skill",
    uri="./custom",
    metadata=SkillMetadata(name="my-skill", description="Custom skill"),
    content="Instructions here",
)
agent = Agent(
    model='openai:gpt-5.2',
    toolsets=[SkillsToolset(skills=[custom_skill])]
)

# Combined mode: both programmatic skills and directories
agent = Agent(
    model='openai:gpt-5.2',
    toolsets=[SkillsToolset(
        skills=[custom_skill],
        directories=["./skills"]
    )]
)

# Using SkillsDirectory instances directly
from pydantic_ai.toolsets.skills import SkillsDirectory

dir1 = SkillsDirectory(path="./skills")
agent = Agent(
    model='openai:gpt-5.2',
    toolsets=[SkillsToolset(directories=[dir1, "./more-skills"])]
)
# Skills instructions are automatically injected via get_instructions()
Source code in pydantic_ai_skills/toolset.py
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
class SkillsToolset(FunctionToolset[Any]):
    """Pydantic AI toolset for automatic skill discovery and integration.

    See [skills docs](../creating-skills.md) for more information.

    This is the primary interface for integrating skills with Pydantic AI agents.
    It manages skills directly and provides tools for skill interaction.

    Provides the following tools to agents:
    - list_skills(): List all available skills
    - load_skill(skill_name): Load a specific skill's instructions
    - read_skill_resource(skill_name, resource_name): Read a skill resource file
    - run_skill_script(skill_name, script_name, args): Execute a skill script

    Example:
        ```python
        from pydantic_ai import Agent, SkillsToolset

        # Default: uses ./skills directory
        agent = Agent(
            model='openai:gpt-5.2',
            instructions="You are a helpful assistant.",
            toolsets=[SkillsToolset()]
        )

        # Multiple directories
        agent = Agent(
            model='openai:gpt-5.2',
            toolsets=[SkillsToolset(directories=["./skills", "./more-skills"])]
        )

        # Programmatic skills
        from pydantic_ai.toolsets.skills import Skill, SkillMetadata

        custom_skill = Skill(
            name="my-skill",
            uri="./custom",
            metadata=SkillMetadata(name="my-skill", description="Custom skill"),
            content="Instructions here",
        )
        agent = Agent(
            model='openai:gpt-5.2',
            toolsets=[SkillsToolset(skills=[custom_skill])]
        )

        # Combined mode: both programmatic skills and directories
        agent = Agent(
            model='openai:gpt-5.2',
            toolsets=[SkillsToolset(
                skills=[custom_skill],
                directories=["./skills"]
            )]
        )

        # Using SkillsDirectory instances directly
        from pydantic_ai.toolsets.skills import SkillsDirectory

        dir1 = SkillsDirectory(path="./skills")
        agent = Agent(
            model='openai:gpt-5.2',
            toolsets=[SkillsToolset(directories=[dir1, "./more-skills"])]
        )
        # Skills instructions are automatically injected via get_instructions()
        ```
    """

    def __init__(
        self,
        *,
        skills: list[Skill] | None = None,
        directories: list[str | Path | SkillsDirectory] | None = None,
        registries: list[SkillRegistry] | None = None,
        validate: bool = True,
        max_depth: int | None = 3,
        id: str | None = None,
        instruction_template: str | None = None,
        exclude_tools: set[str] | list[str] | None = None,
    ) -> None:
        """Initialize the skills toolset.

        Args:
            skills: List of pre-loaded Skill objects. Can be combined with `directories`.
            directories: List of directories or SkillsDirectory instances to discover skills from.
                Can be combined with `skills`. If both are None, defaults to ["./skills"].
                String/Path entries are converted to SkillsDirectory instances.
            registries: List of SkillRegistry instances (e.g. GitSkillsRegistry) to load
                skills from. Registry skills are fetched lazily on the first async call
                (``get_instructions`` or any tool invocation). Can be combined with
                ``skills`` and ``directories``.
            validate: Validate skill structure during discovery (used when creating SkillsDirectory from str/Path).
            max_depth: Maximum depth for skill discovery (None for unlimited, used when creating SkillsDirectory from str/Path).
            id: Unique identifier for this toolset.
            instruction_template: Custom instruction template for skills system prompt.
                Must include `{skills_list}` placeholder. If None, uses default template.
                Tool usage guidance is provided in the tool docstrings themselves.
            exclude_tools: Set or list of tool names to exclude from registration (e.g., ['run_skill_script']).
                Useful for security or capability restrictions such as disabling script execution.
                Valid tool names: 'list_skills', 'load_skill', 'read_skill_resource', 'run_skill_script'.

        Example:
            ```python
            # Default: uses ./skills directory
            toolset = SkillsToolset()

            # Multiple directories
            toolset = SkillsToolset(directories=["./skills", "./more-skills"])

            # Programmatic skills
            toolset = SkillsToolset(skills=[skill1, skill2])

            # Combined mode
            toolset = SkillsToolset(
                skills=[skill1, skill2],
                directories=["./skills", skills_dir_instance]
            )

            # Using SkillsDirectory instances directly
            dir1 = SkillsDirectory(path="./skills")
            toolset = SkillsToolset(directories=[dir1])

            # Excluding specific tools (disable script execution with a set)
            toolset = SkillsToolset(exclude_tools=['run_skill_script'])

            # Git registry: clone a remote repo and load skills
            from pydantic_ai_skills.registries.git import GitSkillsRegistry
            registry = GitSkillsRegistry(
                repo_url="https://github.com/anthropics/skills",
                path="skills",
            )
            toolset = SkillsToolset(registries=[registry])
            ```
        """
        super().__init__(id=id)

        self._instruction_template = instruction_template

        # Validate and initialize exclude_tools
        valid_tools = {'list_skills', 'load_skill', 'read_skill_resource', 'run_skill_script'}
        self._exclude_tools: set[str] = set(exclude_tools or [])
        invalid = self._exclude_tools - valid_tools
        if invalid:
            raise ValueError(f'Unknown tools: {invalid}. Valid: {valid_tools}')

        if 'load_skill' in self._exclude_tools:
            warnings.warn(
                "'load_skill' is a critical tool for skills usage and has been excluded. "
                'Agents will not be able to load skill instructions, which severely limits skill functionality.',
                UserWarning,
                stacklevel=2,
            )

        # Initialize the skills dict and directories list (for refresh)
        self._skills: dict[str, Skill] = {}
        self._skill_directories: list[SkillsDirectory] = []
        self._registries: list[SkillRegistry] = list(registries) if registries else []
        self._validate = validate
        self._max_depth = max_depth

        # Load programmatic skills first (highest priority)
        if skills is not None:
            for skill in skills:
                self._register_skill(skill)

        # Load directory-based skills (second priority)
        if directories is not None:
            self._load_directory_skills(directories)
        elif skills is None and not self._registries:
            # Default: ./skills directory (only if no skills or registries provided)
            default_dir = Path('./skills')
            if not default_dir.exists():
                warnings.warn(
                    f"Default skills directory '{default_dir}' does not exist. No skills will be loaded.",
                    UserWarning,
                    stacklevel=2,
                )
            else:
                self._load_directory_skills([default_dir])

        # Load registry skills (lowest priority — won't override existing)
        self._load_registry_skills()

        # Register tools
        self._register_tools()

    @property
    def skills(self) -> dict[str, Skill]:
        """Get the dictionary of loaded skills.

        Returns:
            Dictionary mapping skill names to Skill objects.
        """
        return self._skills

    def get_skill(self, name: str) -> Skill:
        """Get a specific skill by name.

        Args:
            name: Name of the skill to get.

        Returns:
            The requested Skill object.

        Raises:
            SkillNotFoundError: If skill is not found.
        """
        if name not in self._skills:
            available = ', '.join(sorted(self._skills.keys())) or 'none'
            raise SkillNotFoundError(f"Skill '{name}' not found. Available: {available}")
        return self._skills[name]

    def _load_directory_skills(self, directories: list[str | Path | SkillsDirectory]) -> None:
        """Load skills from configured directories.

        Converts directory specifications to SkillsDirectory instances and
        discovers skills from each directory in a single pass.

        Args:
            directories: List of directory paths or SkillsDirectory instances.
        """
        for directory in directories:
            # Normalize to SkillsDirectory instance
            if isinstance(directory, SkillsDirectory):
                skill_dir = directory
            else:
                skill_dir = SkillsDirectory(
                    path=directory,
                    validate=self._validate,
                    max_depth=self._max_depth,
                )

            # Store for future reference
            self._skill_directories.append(skill_dir)

            # Discover skills from this directory (last one wins)
            for skill in skill_dir.get_skills().values():
                skill_name = skill.name
                if skill_name in self._skills:
                    warnings.warn(
                        f"Duplicate skill '{skill_name}' found. Overriding previous occurrence.",
                        UserWarning,
                        stacklevel=3,
                    )
                self._skills[skill_name] = skill

    def _load_registry_skills(self) -> None:
        """Load skills from all configured registries.

        Calls ``get_skills()`` on each registry and registers the returned
        skills. Skills already registered (from ``skills`` or ``directories``)
        are **not** overridden — registries have the lowest priority.
        """
        for registry in self._registries:
            try:
                registry_skills = registry.get_skills()
            except Exception as exc:
                warnings.warn(
                    f'Failed to load skills from registry {registry!r}: {exc}',
                    UserWarning,
                    stacklevel=2,
                )
                continue
            for skill in registry_skills:
                if skill.name not in self._skills:
                    self._register_skill(skill)

    def _build_resource_xml(self, resource: SkillResource) -> str:
        """Build XML representation of a resource.

        Args:
            resource: The resource to format.

        Returns:
            XML string representation of the resource.
        """
        res_xml = f'<resource name="{resource.name}"'
        if resource.description:
            res_xml += f' description="{resource.description}"'
        if resource.function and resource.function_schema:
            params_json = json.dumps(resource.function_schema.json_schema)
            res_xml += f' parameters={json.dumps(params_json)}'
        res_xml += ' />'
        return res_xml

    def _build_script_xml(self, script: SkillScript) -> str:
        """Build XML representation of a script.

        Args:
            script: The script to format.

        Returns:
            XML string representation of the script.
        """
        scr_xml = f'<script name="{script.name}"'
        if script.description:
            scr_xml += f' description="{script.description}"'
        if script.function and script.function_schema:
            params_json = json.dumps(script.function_schema.json_schema)
            scr_xml += f' parameters={json.dumps(params_json)}'
        scr_xml += ' />'
        return scr_xml

    def _find_skill_resource(self, skill: Skill, resource_name: str) -> SkillResource | None:
        """Find a resource in a skill by name.

        Args:
            skill: The skill to search in.
            resource_name: The resource name to find.

        Returns:
            The resource if found, None otherwise.
        """
        if not skill.resources:
            return None
        for r in skill.resources:
            if r.name == resource_name:
                return r
        return None

    def _find_skill_script(self, skill: Skill, script_name: str) -> SkillScript | None:
        """Find a script in a skill by name.

        Args:
            skill: The skill to search in.
            script_name: The script name to find.

        Returns:
            The script if found, None otherwise.
        """
        if not skill.scripts:
            return None
        for s in skill.scripts:
            if s.name == script_name:
                return s
        return None

    def _register_tools(self) -> None:
        """Register skill management tools with the toolset.

        This method registers skill management tools, excluding any specified in exclude_tools.
        Available tools: list_skills, load_skill, read_skill_resource, run_skill_script.
        """
        if 'list_skills' not in self._exclude_tools:
            self._register_list_skills()
        if 'load_skill' not in self._exclude_tools:
            self._register_load_skill()
        if 'read_skill_resource' not in self._exclude_tools:
            self._register_read_skill_resource()
        if 'run_skill_script' not in self._exclude_tools:
            self._register_run_skill_script()

    def _register_list_skills(self) -> None:
        """Register the list_skills tool."""

        @self.tool
        async def list_skills(_ctx: RunContext[Any]) -> dict[str, str]:  # pyright: ignore[reportUnusedFunction]
            """Get an overview of all available skills and what they do.

            Use this when you need to discover what skills exist or refresh your knowledge
            of available capabilities. Skills provide domain-specific knowledge and instructions
            for specialized tasks.

            Returns:
                Dictionary mapping skill names to their descriptions.
                Empty dictionary if no skills are available.
            """
            return {name: skill.description for name, skill in self._skills.items()}

    def _register_load_skill(self) -> None:
        """Register the load_skill tool."""

        @self.tool
        async def load_skill(ctx: RunContext[Any], skill_name: str) -> str:  # pyright: ignore[reportUnusedFunction]  # noqa: D417
            """Load complete instructions and capabilities for a specific skill.

            A skill contains detailed instructions, supplementary resources (like templates or
            reference docs), and executable scripts. Load a skill when you need to perform a
            task within its domain.

            Args:
                skill_name: Exact name from your available skills list.
                    Must match exactly (e.g., "data-analysis" not "data analysis").

            Returns:
                Structured documentation containing:
                - Skill name, description, and source location
                - Available resources: supplementary files with their parameters
                - Available scripts: executable programs with their parameters
                - Detailed instructions: step-by-step guidance for using the skill

            Important:
            - Read the entire instructions section before taking action
            - Resource and script names are authoritative - use exact names from the output
            - Do NOT infer or guess resource/script names
            - Check parameter schemas if resources or scripts require arguments
            """
            _ = ctx  # Required by Pydantic AI toolset protocol
            if skill_name not in self._skills:
                available = ', '.join(sorted(self._skills.keys())) or 'none'
                raise SkillNotFoundError(f"Skill '{skill_name}' not found. Available: {available}")

            skill = self._skills[skill_name]

            # Build resources list with schemas for callable resources
            resources_parts: list[str] = []
            if skill.resources:
                for res in skill.resources:
                    resources_parts.append(self._build_resource_xml(res))
            resources_list = '\n'.join(resources_parts) if resources_parts else '<!-- No resources -->'

            # Build scripts list with schemas for callable scripts
            scripts_parts: list[str] = []
            if skill.scripts:
                for scr in skill.scripts:
                    scripts_parts.append(self._build_script_xml(scr))
            scripts_list = '\n'.join(scripts_parts) if scripts_parts else '<!-- No scripts -->'

            # Format response
            return LOAD_SKILL_TEMPLATE.format(
                skill_name=skill.name,
                description=skill.description,
                uri=skill.uri or 'N/A',
                resources_list=resources_list,
                scripts_list=scripts_list,
                content=skill.content,
            )

    def _register_read_skill_resource(self) -> None:
        """Register the read_skill_resource tool."""

        @self.tool
        async def read_skill_resource(  # pyright: ignore[reportUnusedFunction]  # noqa: D417
            ctx: RunContext[Any],
            skill_name: str,
            resource_name: str,
            args: dict[str, Any] | None = None,
        ) -> str:
            """Access supplementary documentation, templates, or data from a skill.

            Resources are additional files that support skill execution. They can be static
            content (markdown docs, templates, schemas) or dynamic callables (functions that
            generate content based on parameters).

            When to use this:
            - When a skill's instructions reference a specific resource
            - To access form templates, reference documentation, or data schemas
            - When you need supplementary information beyond the skill instructions

            Args:
                skill_name: Name of the skill containing the resource.
                resource_name: Exact name of the resource as listed in the skill.
                    Examples: "FORMS.md", "REFERENCE.md", "get_schema"
                    Must match exactly - do not infer or guess.
                args: Arguments for callable resources (optional for static files).
                    Keys must match the parameter names in the resource's schema.

            Returns:
                The resource content as a string.

            Important:
            - Get resource names from the skill's documentation first
            - Use exact resource names - do not modify or guess
            - Check if the resource requires arguments (check its schema)
            - Static files don't need args; callables may require them
            """
            if skill_name not in self._skills:
                raise SkillNotFoundError(f"Skill '{skill_name}' not found.")

            skill = self._skills[skill_name]

            # Find the resource
            resource = self._find_skill_resource(skill, resource_name)

            if resource is None:
                available = [r.name for r in skill.resources] if skill.resources else []
                raise SkillResourceNotFoundError(
                    f"Resource '{resource_name}' not found in skill '{skill_name}'. Available: {available}"
                )

            # Use resource.load() interface - implementation handles the details
            return await resource.load(ctx=ctx, args=args)

    def _register_run_skill_script(self) -> None:
        """Register the run_skill_script tool."""

        @self.tool
        async def run_skill_script(  # pyright: ignore[reportUnusedFunction]  # noqa: D417
            ctx: RunContext[Any],
            skill_name: str,
            script_name: str,
            args: dict[str, Any] | None = None,
        ) -> str:
            """Execute a skill script that performs actions or computations.

            Scripts are executable programs provided by skills that can perform actions
            (API calls, file operations), process data (transformations, analysis), or
            generate outputs (reports, visualizations).

            When to use this:
            - When a skill's instructions tell you to run a specific script
            - To perform automated tasks that the skill provides
            - For data processing, API interactions, or file operations

            Args:
                skill_name: Name of the skill containing the script.
                script_name: Exact name of the script as listed in the skill.
                    Usually includes .py extension: "analyze.py", "process.py"
                    Must match exactly - do not infer or guess.
                args: Arguments required by the script.
                    Keys must match the parameter names in the script's schema.

            Returns:
                Script execution output including stdout and stderr.

            Important:
            - Get script names from the skill's documentation first
            - Use exact script names - do not modify or guess
            - Check the script's parameter schema for required arguments
            - Review skill instructions before running scripts
            - Scripts may modify external state (files, databases, APIs)
            - Execution errors are included in the output
            """
            if skill_name not in self._skills:
                raise SkillNotFoundError(f"Skill '{skill_name}' not found.")

            skill = self._skills[skill_name]

            # Find the script
            script = self._find_skill_script(skill, script_name)

            if script is None:
                available = [s.name for s in skill.scripts] if skill.scripts else []
                raise SkillResourceNotFoundError(
                    f"Script '{script_name}' not found in skill '{skill_name}'. Available: {available}"
                )

            # Use script.run() interface - implementation handles the details
            return await script.run(ctx=ctx, args=args)

    async def get_instructions(self, ctx: RunContext[Any]) -> str | None:
        """Return instructions to inject into the agent's system prompt.

        Returns the skills system prompt containing usage guidance and all skill metadata.

        Args:
            ctx: The run context for this agent run.

        Returns:
            The skills system prompt, or None if no skills are loaded.
        """
        if not self._skills:
            return None

        # Build skills list in XML format
        skills_list_lines: list[str] = []
        for skill in sorted(self._skills.values(), key=lambda s: s.name):
            skills_list_lines.append('<skill>')
            skills_list_lines.append(f'<name>{skill.name}</name>')
            skills_list_lines.append(f'<description>{skill.description}</description>')
            if skill.uri:
                skills_list_lines.append(f'<uri>{skill.uri}</uri>')
            skills_list_lines.append('</skill>')
        skills_list = '\n'.join(skills_list_lines)

        # Use custom template if provided, otherwise use default
        if self._instruction_template:
            return self._instruction_template.format(skills_list=skills_list)

        return _INSTRUCTION_SKILLS_HEADER.format(skills_list=skills_list)

    def skill(
        self,
        func: Callable[[], str] | None = None,
        *,
        name: str | None = None,
        description: str | None = None,
        license: str | None = None,
        compatibility: str | None = None,
        metadata: dict[str, Any] | None = None,
        resources: list[SkillResource] | None = None,
        scripts: list[SkillScript] | None = None,
    ) -> Any:
        """Decorator to define a skill using a function.

        The decorated function should return a string containing the skill's instructions/content.
        The skill name is derived from the function name (underscores replaced with hyphens)
        unless explicitly provided via the `name` parameter.

        Example:
            ```python
            from pydantic_ai import RunContext
            from pydantic_ai.toolsets.skills import SkillsToolset

            skills = SkillsToolset()

            @skills.skill(resources=[], metadata={'version': '1.0'})
            def data_analyzer() -> str:
                '''Analyze data from various sources.'''
                return '''
                Use this skill for data analysis tasks.
                The skill provides tools for querying and analyzing data.
                '''

            @data_analyzer.resource
            async def get_schema(ctx: RunContext[MyDeps]) -> str:
                return await ctx.deps.database.get_schema()

            @data_analyzer.script
            async def run_analysis(ctx: RunContext[MyDeps], query: str) -> str:
                result = await ctx.deps.database.execute(query)
                return str(result)
            ```

        Args:
            func: The function that returns skill content (must return str).
            name: Skill name (defaults to normalized function name: underscores → hyphens).
            description: Skill description (inferred from docstring if not provided).
            license: Optional license information (e.g., "Apache-2.0").
            compatibility: Optional environment requirements (e.g., "Requires Python 3.10+").
            metadata: Additional metadata fields as a dictionary.
            resources: Initial list of resources to attach to the skill.
            scripts: Initial list of scripts to attach to the skill.

        Returns:
            A SkillWrapper instance that can be used to attach resources and scripts.
        """

        def decorator(f: Callable[[], str]) -> SkillWrapper[Any]:
            # Derive name from function name if not provided
            if name is not None:
                # Explicit name provided - validate it directly without normalization
                skill_name = name
                # Validate the explicit name
                if not SKILL_NAME_PATTERN.match(skill_name):
                    raise SkillValidationError(
                        f"Skill name '{skill_name}' is invalid. "
                        'Skill names must contain only lowercase letters, numbers, and hyphens '
                        '(no consecutive hyphens).'
                    )
                if len(skill_name) > 64:
                    raise SkillValidationError(
                        f"Skill name '{skill_name}' exceeds 64 characters ({len(skill_name)} chars)."
                    )
            else:
                # Derive and normalize from function name
                skill_name = normalize_skill_name(f.__name__)

            # Extract description from docstring if not provided
            skill_description = description
            if skill_description is None:
                sig = get_signature(f)
                desc, _ = doc_descriptions(f, sig, docstring_format='auto')
                skill_description = desc

            # Create the skill wrapper
            wrapper: SkillWrapper[Any] = SkillWrapper(
                function=f,
                name=skill_name,
                description=skill_description,
                license=license,
                compatibility=compatibility,
                metadata=metadata,
                resources=list(resources) if resources else [],
                scripts=list(scripts) if scripts else [],
            )

            # Register the skill immediately (execute function to get content)
            self._register_skill(wrapper)

            # Return the wrapper so resources/scripts can be attached
            return wrapper

        if func is None:
            # Called with arguments: @skills.skill(name="custom")
            return decorator
        else:
            # Called without arguments: @skills.skill
            return decorator(func)

    def _register_skill(self, skill: Skill | SkillWrapper[Any]) -> None:
        """Register a skill with the toolset.

        Converts SkillWrapper instances to Skill dataclasses before registering.
        Warns about duplicate skill names (last occurrence wins).

        Args:
            skill: Skill or SkillWrapper instance to register.
        """
        # Convert SkillWrapper to Skill if needed
        if isinstance(skill, SkillWrapper):
            skill = skill.to_skill()

        # Warn about duplicates
        if skill.name in self._skills:
            warnings.warn(
                f"Duplicate skill '{skill.name}' found. Overriding previous occurrence.",
                UserWarning,
                stacklevel=3,
            )

        # Register the skill
        self._skills[skill.name] = skill

__init__

__init__(*, skills: list[Skill] | None = None, directories: list[str | Path | SkillsDirectory] | None = None, registries: list[SkillRegistry] | None = None, validate: bool = True, max_depth: int | None = 3, id: str | None = None, instruction_template: str | None = None, exclude_tools: set[str] | list[str] | None = None) -> None

Initialize the skills toolset.

Parameters:

Name Type Description Default
skills list[Skill] | None

List of pre-loaded Skill objects. Can be combined with directories.

None
directories list[str | Path | SkillsDirectory] | None

List of directories or SkillsDirectory instances to discover skills from. Can be combined with skills. If both are None, defaults to ["./skills"]. String/Path entries are converted to SkillsDirectory instances.

None
registries list[SkillRegistry] | None

List of SkillRegistry instances (e.g. GitSkillsRegistry) to load skills from. Registry skills are fetched lazily on the first async call (get_instructions or any tool invocation). Can be combined with skills and directories.

None
validate bool

Validate skill structure during discovery (used when creating SkillsDirectory from str/Path).

True
max_depth int | None

Maximum depth for skill discovery (None for unlimited, used when creating SkillsDirectory from str/Path).

3
id str | None

Unique identifier for this toolset.

None
instruction_template str | None

Custom instruction template for skills system prompt. Must include {skills_list} placeholder. If None, uses default template. Tool usage guidance is provided in the tool docstrings themselves.

None
exclude_tools set[str] | list[str] | None

Set or list of tool names to exclude from registration (e.g., ['run_skill_script']). Useful for security or capability restrictions such as disabling script execution. Valid tool names: 'list_skills', 'load_skill', 'read_skill_resource', 'run_skill_script'.

None
Example
# Default: uses ./skills directory
toolset = SkillsToolset()

# Multiple directories
toolset = SkillsToolset(directories=["./skills", "./more-skills"])

# Programmatic skills
toolset = SkillsToolset(skills=[skill1, skill2])

# Combined mode
toolset = SkillsToolset(
    skills=[skill1, skill2],
    directories=["./skills", skills_dir_instance]
)

# Using SkillsDirectory instances directly
dir1 = SkillsDirectory(path="./skills")
toolset = SkillsToolset(directories=[dir1])

# Excluding specific tools (disable script execution with a set)
toolset = SkillsToolset(exclude_tools=['run_skill_script'])

# Git registry: clone a remote repo and load skills
from pydantic_ai_skills.registries.git import GitSkillsRegistry
registry = GitSkillsRegistry(
    repo_url="https://github.com/anthropics/skills",
    path="skills",
)
toolset = SkillsToolset(registries=[registry])
Source code in pydantic_ai_skills/toolset.py
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
def __init__(
    self,
    *,
    skills: list[Skill] | None = None,
    directories: list[str | Path | SkillsDirectory] | None = None,
    registries: list[SkillRegistry] | None = None,
    validate: bool = True,
    max_depth: int | None = 3,
    id: str | None = None,
    instruction_template: str | None = None,
    exclude_tools: set[str] | list[str] | None = None,
) -> None:
    """Initialize the skills toolset.

    Args:
        skills: List of pre-loaded Skill objects. Can be combined with `directories`.
        directories: List of directories or SkillsDirectory instances to discover skills from.
            Can be combined with `skills`. If both are None, defaults to ["./skills"].
            String/Path entries are converted to SkillsDirectory instances.
        registries: List of SkillRegistry instances (e.g. GitSkillsRegistry) to load
            skills from. Registry skills are fetched lazily on the first async call
            (``get_instructions`` or any tool invocation). Can be combined with
            ``skills`` and ``directories``.
        validate: Validate skill structure during discovery (used when creating SkillsDirectory from str/Path).
        max_depth: Maximum depth for skill discovery (None for unlimited, used when creating SkillsDirectory from str/Path).
        id: Unique identifier for this toolset.
        instruction_template: Custom instruction template for skills system prompt.
            Must include `{skills_list}` placeholder. If None, uses default template.
            Tool usage guidance is provided in the tool docstrings themselves.
        exclude_tools: Set or list of tool names to exclude from registration (e.g., ['run_skill_script']).
            Useful for security or capability restrictions such as disabling script execution.
            Valid tool names: 'list_skills', 'load_skill', 'read_skill_resource', 'run_skill_script'.

    Example:
        ```python
        # Default: uses ./skills directory
        toolset = SkillsToolset()

        # Multiple directories
        toolset = SkillsToolset(directories=["./skills", "./more-skills"])

        # Programmatic skills
        toolset = SkillsToolset(skills=[skill1, skill2])

        # Combined mode
        toolset = SkillsToolset(
            skills=[skill1, skill2],
            directories=["./skills", skills_dir_instance]
        )

        # Using SkillsDirectory instances directly
        dir1 = SkillsDirectory(path="./skills")
        toolset = SkillsToolset(directories=[dir1])

        # Excluding specific tools (disable script execution with a set)
        toolset = SkillsToolset(exclude_tools=['run_skill_script'])

        # Git registry: clone a remote repo and load skills
        from pydantic_ai_skills.registries.git import GitSkillsRegistry
        registry = GitSkillsRegistry(
            repo_url="https://github.com/anthropics/skills",
            path="skills",
        )
        toolset = SkillsToolset(registries=[registry])
        ```
    """
    super().__init__(id=id)

    self._instruction_template = instruction_template

    # Validate and initialize exclude_tools
    valid_tools = {'list_skills', 'load_skill', 'read_skill_resource', 'run_skill_script'}
    self._exclude_tools: set[str] = set(exclude_tools or [])
    invalid = self._exclude_tools - valid_tools
    if invalid:
        raise ValueError(f'Unknown tools: {invalid}. Valid: {valid_tools}')

    if 'load_skill' in self._exclude_tools:
        warnings.warn(
            "'load_skill' is a critical tool for skills usage and has been excluded. "
            'Agents will not be able to load skill instructions, which severely limits skill functionality.',
            UserWarning,
            stacklevel=2,
        )

    # Initialize the skills dict and directories list (for refresh)
    self._skills: dict[str, Skill] = {}
    self._skill_directories: list[SkillsDirectory] = []
    self._registries: list[SkillRegistry] = list(registries) if registries else []
    self._validate = validate
    self._max_depth = max_depth

    # Load programmatic skills first (highest priority)
    if skills is not None:
        for skill in skills:
            self._register_skill(skill)

    # Load directory-based skills (second priority)
    if directories is not None:
        self._load_directory_skills(directories)
    elif skills is None and not self._registries:
        # Default: ./skills directory (only if no skills or registries provided)
        default_dir = Path('./skills')
        if not default_dir.exists():
            warnings.warn(
                f"Default skills directory '{default_dir}' does not exist. No skills will be loaded.",
                UserWarning,
                stacklevel=2,
            )
        else:
            self._load_directory_skills([default_dir])

    # Load registry skills (lowest priority — won't override existing)
    self._load_registry_skills()

    # Register tools
    self._register_tools()

skills property

skills: dict[str, Skill]

Get the dictionary of loaded skills.

Returns:

Type Description
dict[str, Skill]

Dictionary mapping skill names to Skill objects.

get_skill

get_skill(name: str) -> Skill

Get a specific skill by name.

Parameters:

Name Type Description Default
name str

Name of the skill to get.

required

Returns:

Type Description
Skill

The requested Skill object.

Raises:

Type Description
SkillNotFoundError

If skill is not found.

Source code in pydantic_ai_skills/toolset.py
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
def get_skill(self, name: str) -> Skill:
    """Get a specific skill by name.

    Args:
        name: Name of the skill to get.

    Returns:
        The requested Skill object.

    Raises:
        SkillNotFoundError: If skill is not found.
    """
    if name not in self._skills:
        available = ', '.join(sorted(self._skills.keys())) or 'none'
        raise SkillNotFoundError(f"Skill '{name}' not found. Available: {available}")
    return self._skills[name]

get_instructions async

get_instructions(ctx: RunContext[Any]) -> str | None

Return instructions to inject into the agent's system prompt.

Returns the skills system prompt containing usage guidance and all skill metadata.

Parameters:

Name Type Description Default
ctx RunContext[Any]

The run context for this agent run.

required

Returns:

Type Description
str | None

The skills system prompt, or None if no skills are loaded.

Source code in pydantic_ai_skills/toolset.py
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
async def get_instructions(self, ctx: RunContext[Any]) -> str | None:
    """Return instructions to inject into the agent's system prompt.

    Returns the skills system prompt containing usage guidance and all skill metadata.

    Args:
        ctx: The run context for this agent run.

    Returns:
        The skills system prompt, or None if no skills are loaded.
    """
    if not self._skills:
        return None

    # Build skills list in XML format
    skills_list_lines: list[str] = []
    for skill in sorted(self._skills.values(), key=lambda s: s.name):
        skills_list_lines.append('<skill>')
        skills_list_lines.append(f'<name>{skill.name}</name>')
        skills_list_lines.append(f'<description>{skill.description}</description>')
        if skill.uri:
            skills_list_lines.append(f'<uri>{skill.uri}</uri>')
        skills_list_lines.append('</skill>')
    skills_list = '\n'.join(skills_list_lines)

    # Use custom template if provided, otherwise use default
    if self._instruction_template:
        return self._instruction_template.format(skills_list=skills_list)

    return _INSTRUCTION_SKILLS_HEADER.format(skills_list=skills_list)

skill

skill(func: Callable[[], str] | None = None, *, name: str | None = None, description: str | None = None, license: str | None = None, compatibility: str | None = None, metadata: dict[str, Any] | None = None, resources: list[SkillResource] | None = None, scripts: list[SkillScript] | None = None) -> Any

Decorator to define a skill using a function.

The decorated function should return a string containing the skill's instructions/content. The skill name is derived from the function name (underscores replaced with hyphens) unless explicitly provided via the name parameter.

Example
from pydantic_ai import RunContext
from pydantic_ai.toolsets.skills import SkillsToolset

skills = SkillsToolset()

@skills.skill(resources=[], metadata={'version': '1.0'})
def data_analyzer() -> str:
    '''Analyze data from various sources.'''
    return '''
    Use this skill for data analysis tasks.
    The skill provides tools for querying and analyzing data.
    '''

@data_analyzer.resource
async def get_schema(ctx: RunContext[MyDeps]) -> str:
    return await ctx.deps.database.get_schema()

@data_analyzer.script
async def run_analysis(ctx: RunContext[MyDeps], query: str) -> str:
    result = await ctx.deps.database.execute(query)
    return str(result)

Parameters:

Name Type Description Default
func Callable[[], str] | None

The function that returns skill content (must return str).

None
name str | None

Skill name (defaults to normalized function name: underscores → hyphens).

None
description str | None

Skill description (inferred from docstring if not provided).

None
license str | None

Optional license information (e.g., "Apache-2.0").

None
compatibility str | None

Optional environment requirements (e.g., "Requires Python 3.10+").

None
metadata dict[str, Any] | None

Additional metadata fields as a dictionary.

None
resources list[SkillResource] | None

Initial list of resources to attach to the skill.

None
scripts list[SkillScript] | None

Initial list of scripts to attach to the skill.

None

Returns:

Type Description
Any

A SkillWrapper instance that can be used to attach resources and scripts.

Source code in pydantic_ai_skills/toolset.py
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
def skill(
    self,
    func: Callable[[], str] | None = None,
    *,
    name: str | None = None,
    description: str | None = None,
    license: str | None = None,
    compatibility: str | None = None,
    metadata: dict[str, Any] | None = None,
    resources: list[SkillResource] | None = None,
    scripts: list[SkillScript] | None = None,
) -> Any:
    """Decorator to define a skill using a function.

    The decorated function should return a string containing the skill's instructions/content.
    The skill name is derived from the function name (underscores replaced with hyphens)
    unless explicitly provided via the `name` parameter.

    Example:
        ```python
        from pydantic_ai import RunContext
        from pydantic_ai.toolsets.skills import SkillsToolset

        skills = SkillsToolset()

        @skills.skill(resources=[], metadata={'version': '1.0'})
        def data_analyzer() -> str:
            '''Analyze data from various sources.'''
            return '''
            Use this skill for data analysis tasks.
            The skill provides tools for querying and analyzing data.
            '''

        @data_analyzer.resource
        async def get_schema(ctx: RunContext[MyDeps]) -> str:
            return await ctx.deps.database.get_schema()

        @data_analyzer.script
        async def run_analysis(ctx: RunContext[MyDeps], query: str) -> str:
            result = await ctx.deps.database.execute(query)
            return str(result)
        ```

    Args:
        func: The function that returns skill content (must return str).
        name: Skill name (defaults to normalized function name: underscores → hyphens).
        description: Skill description (inferred from docstring if not provided).
        license: Optional license information (e.g., "Apache-2.0").
        compatibility: Optional environment requirements (e.g., "Requires Python 3.10+").
        metadata: Additional metadata fields as a dictionary.
        resources: Initial list of resources to attach to the skill.
        scripts: Initial list of scripts to attach to the skill.

    Returns:
        A SkillWrapper instance that can be used to attach resources and scripts.
    """

    def decorator(f: Callable[[], str]) -> SkillWrapper[Any]:
        # Derive name from function name if not provided
        if name is not None:
            # Explicit name provided - validate it directly without normalization
            skill_name = name
            # Validate the explicit name
            if not SKILL_NAME_PATTERN.match(skill_name):
                raise SkillValidationError(
                    f"Skill name '{skill_name}' is invalid. "
                    'Skill names must contain only lowercase letters, numbers, and hyphens '
                    '(no consecutive hyphens).'
                )
            if len(skill_name) > 64:
                raise SkillValidationError(
                    f"Skill name '{skill_name}' exceeds 64 characters ({len(skill_name)} chars)."
                )
        else:
            # Derive and normalize from function name
            skill_name = normalize_skill_name(f.__name__)

        # Extract description from docstring if not provided
        skill_description = description
        if skill_description is None:
            sig = get_signature(f)
            desc, _ = doc_descriptions(f, sig, docstring_format='auto')
            skill_description = desc

        # Create the skill wrapper
        wrapper: SkillWrapper[Any] = SkillWrapper(
            function=f,
            name=skill_name,
            description=skill_description,
            license=license,
            compatibility=compatibility,
            metadata=metadata,
            resources=list(resources) if resources else [],
            scripts=list(scripts) if scripts else [],
        )

        # Register the skill immediately (execute function to get content)
        self._register_skill(wrapper)

        # Return the wrapper so resources/scripts can be attached
        return wrapper

    if func is None:
        # Called with arguments: @skills.skill(name="custom")
        return decorator
    else:
        # Called without arguments: @skills.skill
        return decorator(func)

options: members: - init - get_instructions - get_skill - skills show_source: true heading_level: 2

Constructor Parameters

The SkillsToolset.__init__() accepts the following parameters:

Parameter Type Default Description
skills list[Skill] \| None None Pre-loaded Skill objects. Can be combined with directories.
directories list[str \| Path \| SkillsDirectory] \| None None Directories or SkillsDirectory instances to discover skills from. Defaults to ["./skills"] if neither skills nor directories provided.
registries list[SkillRegistry] \| None None List of SkillRegistry instances (e.g. GitSkillsRegistry) to load skills from. Can be combined with skills and directories. Registries have the lowest priority.
validate bool True Validate skill structure during discovery. Used when creating SkillsDirectory from str/Path entries.
max_depth int \| None 3 Maximum depth for skill discovery. None for unlimited depth. Used when creating SkillsDirectory from str/Path entries.
id str \| None None Unique identifier for this toolset.
instruction_template str \| None None Custom instruction template for skills system prompt. Must include {skills_list} placeholder. If None, uses default template.

Properties

Property Type Description
skills dict[str, Skill] Dictionary of all available skills, keyed by skill name.

Methods

Method Description
get_skill(skill_name: str) -> Skill Retrieve a specific skill by name. Raises SkillNotFoundError if not found.
get_instructions(ctx: RunContext[Any]) -> str Returns formatted system prompt with skills instructions. Used via @agent.instructions.

Usage Examples

Initialize with File-Based Skills

from pydantic_ai_skills import SkillsToolset

# Basic initialization - defaults to ./skills directory
toolset = SkillsToolset()

# Explicit single directory
toolset = SkillsToolset(directories=["./skills"])

# Multiple directories
toolset = SkillsToolset(
    directories=["./skills", "./shared", "./custom"],
    validate=True,
    max_depth=3,
    id="my-skills"
)

# Using SkillsDirectory instances directly
from pydantic_ai.toolsets.skills import SkillsDirectory

skills_dir = SkillsDirectory(
    path="./skills",
    validate=True,
    max_depth=3
)
toolset = SkillsToolset(directories=[skills_dir])

Initialize with Git Registry

from pydantic_ai_skills import SkillsToolset
from pydantic_ai_skills.registries import GitSkillsRegistry, GitCloneOptions

# Clone a remote Git repository and load its skills
registry = GitSkillsRegistry(
    repo_url='https://github.com/anthropics/skills',
    path='skills',
    target_dir='./anthropics-skills',
    clone_options=GitCloneOptions(depth=1, single_branch=True),
)

toolset = SkillsToolset(registries=[registry])

# Combine with local skills
toolset = SkillsToolset(
    directories=['./skills'],
    registries=[registry],
)

See Skill Registries for composition patterns (filtering, prefixing, combining).

Initialize with Programmatic Skills

from pydantic_ai import RunContext
from pydantic_ai.toolsets.skills import Skill, SkillsToolset

# Create a simple programmatic skill
my_skill = Skill(
    name='custom-skill',
    description='Custom programmatic skill',
    content='Instructions for this skill...'
)

# Initialize toolset with programmatic skill
toolset = SkillsToolset(skills=[my_skill])

# Use the @skill() decorator to define skills inline
skills = SkillsToolset()

@skills.skill()
def data_analyzer() -> str:
    """Analyze data from various sources."""
    return "Provide data analysis capabilities..."

@data_analyzer.resource
def get_schema() -> str:
    """Get available schema information."""
    return "## Schema\n\nAvailable columns..."

@data_analyzer.script
async def analyze(ctx: RunContext[MyDeps], query: str) -> str:
    """Run analysis query."""
    return await ctx.deps.database.execute(query)

Mix File-Based and Programmatic Skills

from pydantic_ai.toolsets.skills import Skill, SkillsToolset

# Create programmatic skills
programmatic_skill = Skill(
    name='runtime-skill',
    description='Created at runtime',
    content='Dynamic skill content...'
)

# Combine both types in a single toolset
toolset = SkillsToolset(
    directories=["./skills"],        # File-based skills from directory
    skills=[programmatic_skill],     # Programmatic skills
    max_depth=3                       # Limit directory discovery depth
)

# Programmatic skills can also be added via decorator
@toolset.skill()
def extra_skill() -> str:
    return "Additional dynamically-defined skill..."

print(f"Total skills loaded: {len(toolset.skills)}")

Custom Instruction Template

from pydantic_ai import Agent
from pydantic_ai.toolsets.skills import SkillsToolset

custom_instructions = """\
You have specialized skills available for specific domains.

Each skill includes instructions, resources, and executable scripts.

Available skills:
{skills_list}

Use `load_skill` to explore any skill that's relevant to the user's request.
"""

toolset = SkillsToolset(
    directories=["./skills"],
    instruction_template=custom_instructions
)

agent = Agent(
    model='openai:gpt-4o',
    toolsets=[toolset]
)

Use @skill() Decorator

from pydantic_ai.toolsets.skills import SkillsToolset

skills = SkillsToolset(directories=["./skills"])

@skills.skill(
    name='custom-analyzer',  # Override function name
    license='Apache-2.0',
    compatibility='Python 3.10+',
    metadata={'version': '1.0.0', 'author': 'my-team'}
)
def data_analyzer() -> str:
    """Analyze data from various sources."""
    return """
# Data Analysis Skill

Use this skill to analyze datasets and generate insights.

## Instructions

Load the full skill with `load_skill` to see available resources and scripts.
"""

# Now 'data-analyzer' skill is registered and available to agents

Get Skills Instructions for Agent

from pydantic_ai import Agent, RunContext
from pydantic_ai_skills import SkillsToolset

toolset = SkillsToolset(directories=["./skills"])

agent = Agent(
    model='openai:gpt-4o',
    instructions="You are a helpful assistant.",
    toolsets=[toolset]
)

@agent.instructions
async def add_skills(ctx: RunContext) -> str | None:
    """Inject skills instructions into agent context."""
    return toolset.get_instructions(ctx)

# The agent will receive skill metadata in system prompt
result = agent.run_sync('Analyze the quarterly data')

The instructions include: - List of available skills with descriptions - How to use the four skill tools - Best practices for progressive disclosure

Access Skills

# Get all skills
all_skills = toolset.skills

# Get specific skill
skill = toolset.get_skill("arxiv-search")

print(f"Name: {skill.name}")
print(f"Description: {skill.metadata.description}")
print(f"Scripts: {[s.name for s in skill.scripts]}")

Tools Provided

The SkillsToolset automatically registers four tools with agents:

list_skills()

Lists all available skills with descriptions.

Returns: Formatted markdown string

Example:

# Available Skills

## arxiv-search

Search arXiv for research papers (scripts: arxiv_search)

## web-research

Structured approach to web research

load_skill(skill_name: str)

Loads full instructions for a specific skill.

Parameters:

  • skill_name (str): Name of the skill to load

Returns: Full skill content including metadata and instructions

read_skill_resource(skill_name: str, resource_name: str)

Reads a resource file from a skill.

Parameters:

  • skill_name (str): Name of the skill
  • resource_name (str): Resource filename (e.g., "REFERENCE.md")

Returns: Resource file content

run_skill_script(skill_name: str, script_name: str, args: dict[str, Any] | None = None)

Executes a skill script with optional arguments.

Parameters:

  • skill_name (str): Name of the skill
  • script_name (str): Name of the script within the skill
  • args (dict[str, Any], optional): Dictionary of arguments to pass to the script
  • For file-based scripts: Converted to command-line flags (e.g., {"query": "test"}--query test)
  • For callable scripts: Passed as function arguments

Returns: String output from script execution

Raises:

  • SkillNotFoundError: If the skill doesn't exist
  • SkillScriptNotFoundError: If the script doesn't exist in the skill
  • SkillScriptExecutionError: If script execution fails or times out

Example:

# Agent calls the tool
agent.run_sync('Run the arxiv search script with query "machine learning"')

# Internally calls:
# result = await toolset.run_skill_script(
#     'arxiv-search',
#     'arxiv_search',
#     {'query': 'machine learning'}
# )

Decorator: @toolset.skill()

The @toolset.skill() decorator enables defining skills directly on the toolset instance.

Signature:

def skill(
    func: Callable[[], str] | None = None,
    *,
    name: str | None = None,
    description: str | None = None,
    license: str | None = None,
    compatibility: str | None = None,
    metadata: dict[str, Any] | None = None,
    resources: list[SkillResource] | None = None,
    scripts: list[SkillScript] | None = None,
) -> SkillWrapper[Any]

Parameters:

Parameter Type Description
func Callable[[], str] Function returning skill instructions/content. Used as decorator.
name str \| None Override skill name (default: normalize function name). Must match ^[a-z0-9]+(-[a-z0-9]+)*$, max 64 chars.
description str \| None Skill description (default: function docstring). Max 1024 chars.
license str \| None License identifier (e.g., "Apache-2.0").
compatibility str \| None Environment/dependency requirements (e.g., "Requires git, docker"). Max 500 chars.
metadata dict[str, Any] \| None Custom metadata fields (e.g., version, author, tags).
resources list[SkillResource] \| None Initial resources to attach. Can be extended with @skill.resource.
scripts list[SkillScript] \| None Initial scripts to attach. Can be extended with @skill.script.

Returns: SkillWrapper[Any] - Decorated skill that supports @skill.resource and @skill.script decorators

Example:

from pydantic_ai.toolsets.skills import SkillsToolset

skills = SkillsToolset()

@skills.skill(
    name='data-analyzer',
    license='MIT',
    compatibility='Python 3.10+',
    metadata={'version': '1.0.0', 'author': 'data-team'}
)
def my_analyzer() -> str:
    """Analyze and process data."""
    return "# Data Analysis Skill\n\nUse for data analysis tasks."

# Extended with resources and scripts
@my_analyzer.resource
def get_schema() -> str:
    return "## Schema\n\nDatabase schema information..."

@my_analyzer.script
async def analyze_data(query: str) -> str:
    return f"Analyzed: {query}"

See Advanced Features for detailed decorator documentation.

See Also