### Setup Project Environment Source: https://github.com/ggozad/haiku.skills/blob/main/docs/development.md Initializes the project by cloning the repository and synchronizing dependencies using the uv package manager. This ensures all required extras are installed for development. ```bash git clone https://github.com/ggozad/haiku.skills.git cd haiku.skills uv sync --all-extras ``` -------------------------------- ### Install Haiku Skills Web Package Source: https://github.com/ggozad/haiku.skills/blob/main/docs/examples.md Command to install the Haiku skills web package, which provides web search and page content extraction capabilities. Requires the BRAVE_API_KEY environment variable for search. ```bash uv add haiku-skills-web ``` -------------------------------- ### Install Graphiti Memory Skill Source: https://github.com/ggozad/haiku.skills/blob/main/docs/examples.md Installs the haiku-skills-graphiti-memory package via uv. This package enables knowledge graph memory capabilities using FalkorDB. ```bash uv add haiku-skills-graphiti-memory ``` -------------------------------- ### Install Haiku Skills Image Generation Package Source: https://github.com/ggozad/haiku.skills/blob/main/docs/examples.md Command to install the Haiku skills image generation package, which enables image generation using Ollama. ```bash uv add haiku-skills-image-generation ``` -------------------------------- ### Build and Preview Documentation Source: https://github.com/ggozad/haiku.skills/blob/main/docs/development.md Generates project documentation using mkdocs. Supports both a strict build process and a local development server for previewing changes. ```bash uv run mkdocs build --strict uv run mkdocs serve ``` -------------------------------- ### Install Built-in Skill Packages Source: https://context7.com/ggozad/haiku.skills/llms.txt Commands to add pre-built skill packages to a project using the uv package manager. ```bash uv add haiku-skills-web uv add haiku-skills-image-generation uv add haiku-skills-code-execution uv add haiku-skills-graphiti-memory ``` -------------------------------- ### Install haiku.skills dependency Source: https://github.com/ggozad/haiku.skills/blob/main/README.md Install the haiku.skills package using the uv package manager. ```bash uv add haiku.skills ``` -------------------------------- ### Initialize SkillToolset and Agent in Python Source: https://github.com/ggozad/haiku.skills/blob/main/docs/quickstart.md This Python code demonstrates how to set up the SkillToolset to discover skills from a specified directory and integrate it with a Haiku Agent. It configures the agent with instructions generated from the skill catalog and shows how to run a query. ```python from pathlib import Path from pydantic_ai import Agent from haiku.skills import SkillToolset, build_system_prompt toolset = SkillToolset( skill_paths=[Path("./skills")], skill_model="openai:gpt-4o-mini", # optional: model to use for skill sub-agents ) agent = Agent( "anthropic:claude-sonnet-4-5-20250929", instructions=build_system_prompt(toolset.skill_catalog), toolsets=[toolset], ) result = await agent.run("Analyze this dataset.") print(result.output) ``` -------------------------------- ### Install Haiku Skills Source: https://context7.com/ggozad/haiku.skills/llms.txt Installs the Haiku Skills core package and optional TUI interface using uv or pip. ```bash # Using uv (recommended) uv add haiku.skills # Using pip pip install haiku.skills # With optional TUI chat interface uv add "haiku.skills[tui]" ``` -------------------------------- ### Install Haiku Skills Code Execution Package Source: https://github.com/ggozad/haiku.skills/blob/main/docs/examples.md Command to install the Haiku skills code execution package, which provides sandboxed Python execution capabilities using pydantic-monty. ```bash uv add haiku-skills-code-execution ``` -------------------------------- ### Discover Entrypoint Skills via Haiku CLI (Bash) Source: https://github.com/ggozad/haiku.skills/blob/main/docs/skill-sources.md Provides examples of using Haiku CLI commands to list and chat with skills, enabling entrypoint discovery. The `--use-entrypoints` flag is crucial for this functionality. ```bash haiku-skills list --use-entrypoints haiku-skills chat --use-entrypoints -m openai:gpt-4o ``` -------------------------------- ### Initialize SkillToolset and Agent Source: https://github.com/ggozad/haiku.skills/blob/main/README.md Demonstrates how to initialize a SkillToolset from a directory of skills and attach it to a pydantic-ai Agent. This setup enables the agent to utilize isolated sub-agents for skill execution. ```python from pathlib import Path from pydantic_ai import Agent from haiku.skills import SkillToolset, build_system_prompt toolset = SkillToolset(skill_paths=[Path("./skills")]) agent = Agent( "anthropic:claude-sonnet-4-5-20250929", instructions=build_system_prompt(toolset.skill_catalog), toolsets=[toolset], ) result = await agent.run("Analyze this dataset.") print(result.output) ``` -------------------------------- ### Register Skill via Entrypoint with Python Source: https://github.com/ggozad/haiku.skills/blob/main/docs/examples.md Shows how to create a minimal Python package that registers a skill with tools and state using package entrypoints. This allows the skill to be discovered and used by Haiku. ```toml [project] name = "my-skill-package" version = "0.1.0" dependencies = ["haiku.skills"] [project.entry-points."haiku.skills"] calculator = "my_skill_package:create_skill" ``` ```python from pydantic import BaseModel from pydantic_ai import RunContext from haiku.skills import Skill, SkillMetadata, SkillSource from haiku.skills.state import SkillRunDeps class CalculatorState(BaseModel): history: list[str] = [] def add(ctx: RunContext[SkillRunDeps], a: float, b: float) -> float: """Add two numbers.""" result = a + b if ctx.deps and ctx.deps.state and isinstance(ctx.deps.state, CalculatorState): ctx.deps.state.history.append(f"{a} + {b} = {result}") return result def create_skill() -> Skill: return Skill( metadata=SkillMetadata( name="calculator", description="Perform mathematical calculations.", ), source=SkillSource.ENTRYPOINT, instructions="Use the add tool to add numbers.", tools=[add], state_type=CalculatorState, state_namespace="calculator", ) ``` ```python from haiku.skills import SkillToolset toolset = SkillToolset(use_entrypoints=True) ``` -------------------------------- ### Configure Multi-Source Skill Toolset Source: https://github.com/ggozad/haiku.skills/blob/main/docs/examples.md Demonstrates how to combine filesystem skills, entrypoint skills, and MCP (Model Context Protocol) skills into a single SkillToolset. The resulting toolset is then integrated into a Pydantic AI agent to provide extended functionality. ```python from pathlib import Path from pydantic_ai.mcp import MCPServerStdio from pydantic_ai import Agent from haiku.skills import SkillToolset, build_system_prompt, skill_from_mcp mcp_skill = skill_from_mcp( MCPServerStdio("uvx", args=["my-mcp-server"]), name="my-mcp-skill", description="Tools from my MCP server.", ) toolset = SkillToolset( skill_paths=[Path("./skills")], # Filesystem skills use_entrypoints=True, # Entrypoint skills skills=[mcp_skill], # MCP skills skill_model="openai:gpt-4o-mini", # Model for skill sub-agents ) agent = Agent( "anthropic:claude-sonnet-4-5-20250929", instructions=build_system_prompt(toolset.skill_catalog), toolsets=[toolset], ) ``` -------------------------------- ### SKILL.md Format Example Source: https://context7.com/ggozad/haiku.skills/llms.txt Illustrates the structure of a SKILL.md file, including YAML frontmatter for metadata and markdown for instructions and workflow. ```markdown --- name: my-skill description: A brief description of what the skill does. license: MIT resources: - data/reference.txt - templates/output.md --- # My Skill Detailed instructions for the sub-agent go here. This content becomes the system prompt when the skill is executed. ## Workflow 1. First, analyze the user request 2. Use available tools to gather information 3. Return a comprehensive response ## Guidelines - Be specific and accurate - Always cite sources when applicable ``` -------------------------------- ### Create Filesystem Skill with Python Source: https://github.com/ggozad/haiku.skills/blob/main/docs/examples.md Demonstrates how to create a skill using a directory structure with SKILL.md, Python scripts, and resource files. The Python script uses pandas for data analysis and can be integrated into an agent. ```python # /// script # dependencies = ["pandas"] # /// """Analyze data.""" import sys import pandas as pd def main(data: str, operation: str = "describe") -> str: """Analyze the given data. Args: data: Input data to analyze. operation: Analysis operation to perform. """ df = pd.read_csv(pd.io.common.StringIO(data)) if operation == "describe": return df.describe().to_string() return f"Analyzed {len(df)} rows" if __name__ == "__main__": data = sys.argv[1] operation = sys.argv[2] if len(sys.argv) > 2 else "describe" print(main(data, operation)) ``` ```python from pathlib import Path from pydantic_ai import Agent from haiku.skills import SkillToolset, build_system_prompt toolset = SkillToolset(skill_paths=[Path("./my-skill")]) agent = Agent( "anthropic:claude-sonnet-4-5-20250929", instructions=build_system_prompt(toolset.skill_catalog), toolsets=[toolset], ) ``` -------------------------------- ### Wrap MCP Server as a Skill with Python Source: https://github.com/ggozad/haiku.skills/blob/main/docs/examples.md Demonstrates how to wrap an existing MCP server as a Haiku skill. This allows the tools provided by the MCP server to be used within the Haiku agent. ```python from pydantic_ai.mcp import MCPServerStdio from pydantic_ai import Agent from haiku.skills import SkillToolset, build_system_prompt, skill_from_mcp skill = skill_from_mcp( MCPServerStdio("uvx", args=["my-mcp-server"]), name="my-mcp-skill", description="Tools from my MCP server.", instructions="Use these tools when the user asks about...", ) toolset = SkillToolset(skills=[skill]) agent = Agent( "anthropic:claude-sonnet-4-5-20250929", instructions=build_system_prompt(toolset.skill_catalog), toolsets=[toolset], ) ``` -------------------------------- ### Execute Tests Source: https://github.com/ggozad/haiku.skills/blob/main/docs/development.md Runs the project test suite using pytest. Includes options for standard execution and coverage reporting, which is required to be at 100%. ```bash uv run pytest uv run pytest --cov ``` -------------------------------- ### Lint and Format Code Source: https://github.com/ggozad/haiku.skills/blob/main/docs/development.md Ensures code quality and consistency using ruff. This performs both linting checks and formatting verification. ```bash uv run ruff check uv run ruff format --check ``` -------------------------------- ### Define a Haiku Skill with YAML Frontmatter Source: https://github.com/ggozad/haiku.skills/blob/main/docs/quickstart.md This snippet shows the structure of a SKILL.md file, which defines a skill for Haiku. It includes YAML frontmatter for metadata like name and description, followed by the main instructions for the agent. ```markdown --- name: my-skill description: Helps with data analysis tasks. --- # My Skill Instructions for the agent go here... ``` -------------------------------- ### Perform Type Checking Source: https://github.com/ggozad/haiku.skills/blob/main/docs/development.md Validates type annotations throughout the codebase using the configured type checker. ```bash uv run ty check ``` -------------------------------- ### Stream Real-time AG-UI Events Source: https://github.com/ggozad/haiku.skills/blob/main/docs/ag-ui.md Illustrates how to use run_agui_stream to merge main-agent events and sub-agent activity events into a single stream, including an example for HTTP streaming responses. ```python from pydantic_ai.ag_ui import AGUIAdapter from haiku.skills import SkillToolset, run_agui_stream toolset = SkillToolset(skills=[skill]) agent = Agent(model, instructions=..., toolsets=[toolset]) adapter = AGUIAdapter(agent=agent, run_input=run_input) async with run_agui_stream(toolset, adapter) as stream: async for event in stream: # Main-agent events and sub-agent activity events arrive here ... # HTTP streaming example async def stream_chat(request): adapter = AGUIAdapter(agent=agent, run_input=run_input, accept=accept) async def event_stream(): async with run_agui_stream(toolset, adapter, deps=SkillDeps()) as stream: async for chunk in adapter.encode_stream(stream): yield chunk return StreamingResponse(event_stream(), media_type=accept) ``` -------------------------------- ### Manage VCR Integration Tests Source: https://github.com/ggozad/haiku.skills/blob/main/docs/development.md Handles integration tests that interface with Ollama. Tests can be run from existing cassettes or recorded as new episodes to update the test data. ```bash # Run from cassettes (default) uv run pytest tests/test_integration.py # Record new cassettes uv run pytest tests/test_integration.py --record-mode=new_episodes ``` -------------------------------- ### Initialize Agent with SkillToolset and SkillDeps Source: https://github.com/ggozad/haiku.skills/blob/main/docs/ag-ui.md Demonstrates how to configure a pydantic-ai Agent using SkillToolset and the SkillDeps dataclass to enable state management. This setup is intended for use with the AG-UI adapter in a FastAPI route. ```python from pydantic_ai import Agent from pydantic_ai.ag_ui import handle_ag_ui_request from haiku.skills import SkillDeps, SkillToolset, build_system_prompt toolset = SkillToolset(use_entrypoints=True) agent = Agent( "anthropic:claude-sonnet-4-5-20250929", instructions=build_system_prompt(toolset.skill_catalog), toolsets=[toolset], deps_type=SkillDeps, ) # In your FastAPI route: # return await handle_ag_ui_request(agent, request, deps=SkillDeps()) ``` -------------------------------- ### Stream AG-UI Events with Sub-Agent Tool Calls Source: https://context7.com/ggozad/haiku.skills/llms.txt Integrate with the AG-UI protocol to stream events and perform real-time sub-agent tool calls. This example demonstrates streaming conversation events and setting up an HTTP endpoint using FastAPI. ```python from pydantic_ai import Agent from pydantic_ai.ag_ui import AGUIAdapter from haiku.skills import SkillDeps, SkillToolset, build_system_prompt, run_agui_stream toolset = SkillToolset(use_entrypoints=True) agent = Agent( "anthropic:claude-sonnet-4-5-20250929", instructions=build_system_prompt(toolset.skill_catalog), toolsets=[toolset], deps_type=SkillDeps, ) # Stream events with real-time sub-agent updates async def stream_conversation(user_message: str): adapter = AGUIAdapter(agent=agent, run_input=user_message) async with run_agui_stream(toolset, adapter, deps=SkillDeps()) as stream: async for event in stream: # Main-agent events and sub-agent activity events arrive here print(f"Event type: {event.type}") if hasattr(event, 'content'): print(f"Content: {event.content}") # HTTP endpoint example (FastAPI) from fastapi import FastAPI from fastapi.responses import StreamingResponse app = FastAPI() @app.post("/chat") async def chat(request: dict): adapter = AGUIAdapter(agent=agent, run_input=request["message"]) async def event_stream(): async with run_agui_stream(toolset, adapter, deps=SkillDeps()) as stream: async for chunk in adapter.encode_stream(stream): yield chunk return StreamingResponse(event_stream(), media_type="text/event-stream") ``` -------------------------------- ### Get JSON Schemas and Introspect Skill State Source: https://context7.com/ggozad/haiku.skills/llms.txt Retrieve JSON schemas for all namespaces and introspect the state metadata of a skill. This is useful for understanding the structure of skill states and their properties. ```python # Get JSON schemas for all namespaces print(toolset.state_schemas) # Output: {"search": {"type": "object", "properties": {...}}} # Introspect skill state metadata meta = skill.state_metadata() print(f"Namespace: {meta.namespace}, Type: {meta.type.__name__}") ``` -------------------------------- ### Initialize SkillToolset and Agent Source: https://context7.com/ggozad/haiku.skills/llms.txt Demonstrates initializing a SkillToolset with filesystem discovery and building a pydantic-ai Agent with a skill-aware system prompt. ```python from pathlib import Path from pydantic_ai import Agent from haiku.skills import SkillToolset, build_system_prompt # Create toolset with filesystem discovery toolset = SkillToolset( skill_paths=[Path("./skills")], # Scan for SKILL.md directories use_entrypoints=True, # Load from Python entrypoints skill_model="openai:gpt-4o-mini", # Model for skill sub-agents ) # Build agent with skill-aware system prompt agent = Agent( "anthropic:claude-sonnet-4-5-20250929", instructions=build_system_prompt(toolset.skill_catalog), toolsets=[toolset], ) # Run the agent result = await agent.run("Search the web for Python best practices") print(result.output) ``` -------------------------------- ### Initialize and Use SkillToolset Source: https://context7.com/ggozad/haiku.skills/llms.txt Demonstrates how to initialize a SkillToolset with auto-discovery enabled and integrate it into a pydantic-ai Agent. ```python from haiku.skills import SkillToolset, build_system_prompt from pydantic_ai import Agent toolset = SkillToolset(use_entrypoints=True) agent = Agent( "anthropic:claude-sonnet-4-5-20250929", instructions=build_system_prompt(toolset.skill_catalog), toolsets=[toolset], ) result = await agent.run("Search for the latest Python 3.13 features") ``` -------------------------------- ### Enable Entrypoint Skill Discovery in SkillToolset (Python) Source: https://github.com/ggozad/haiku.skills/blob/main/docs/skill-sources.md Demonstrates how to configure `SkillToolset` to automatically discover and load skills exposed via Python entrypoints. This simplifies skill management by avoiding explicit path configurations. ```python from haiku.skills import SkillToolset toolset = SkillToolset(use_entrypoints=True) ``` -------------------------------- ### Register Skills via Python Entrypoints Source: https://context7.com/ggozad/haiku.skills/llms.txt Demonstrates how to expose a skill as a package entrypoint in pyproject.toml and discover it programmatically using the SkillToolset class. ```toml [project.entry-points."haiku.skills"] my-skill = "my_package.skills:create_skill" ``` ```python from haiku.skills import Skill, SkillMetadata, SkillSource, SkillToolset def create_skill() -> Skill: return Skill( metadata=SkillMetadata(name="my-skill", description="Data analysis skill."), source=SkillSource.ENTRYPOINT, instructions="# My Skill\n\nAnalyze data using available tools.", tools=[analyze_data, summarize_results], ) toolset = SkillToolset(use_entrypoints=True) print(f"Discovered skills: {toolset.registry.names}") ``` -------------------------------- ### Discover Filesystem Skills with SkillToolset (Python) Source: https://github.com/ggozad/haiku.skills/blob/main/docs/skill-sources.md Shows how to initialize `SkillToolset` to discover skills located in filesystem directories. It scans specified paths for directories containing a `SKILL.md` file, enabling automatic skill loading. ```python from pathlib import Path from haiku.skills import SkillToolset toolset = SkillToolset(skill_paths=[Path("./skills")]) ``` -------------------------------- ### Create executable script tools Source: https://github.com/ggozad/haiku.skills/blob/main/docs/skills.md Shows how to create a script tool with PEP 723 dependency metadata. Scripts containing a main function are automatically parsed into typed tools. ```python # /// script # dependencies = ["pandas"] # /// """Analyze data.""" import sys import pandas as pd def main(data: str, operation: str = "describe") -> str: """Analyze the given data. Args: data: Input data to analyze. operation: Analysis operation to perform. """ df = pd.read_csv(pd.io.common.StringIO(data)) if operation == "describe": return df.describe().to_string() return f"Analyzed {len(df)} rows" if __name__ == "__main__": data = sys.argv[1] operation = sys.argv[2] if len(sys.argv) > 2 else "describe" print(main(data, operation)) ``` -------------------------------- ### Combine Skill Sources in SkillToolset (Python) Source: https://github.com/ggozad/haiku.skills/blob/main/docs/skill-sources.md Demonstrates how to create a `SkillToolset` that aggregates skills from filesystem paths, Python entrypoints, and MCP servers. This allows for a comprehensive skill set in a single toolset instance. ```python from pathlib import Path from pydantic_ai.mcp import MCPServerStdio from haiku.skills import SkillToolset, skill_from_mcp mcp_skill = skill_from_mcp( MCPServerStdio("uvx", args=["my-mcp-server"]), name="my-mcp-skill", description="Tools from my MCP server.", ) toolset = SkillToolset( skill_paths=[Path("./skills")], # Filesystem use_entrypoints=True, # Entrypoints skills=[mcp_skill], # MCP (or any programmatic skill) ) ``` -------------------------------- ### Discover Skills from Filesystem Source: https://context7.com/ggozad/haiku.skills/llms.txt Shows two methods for discovering skills from directories containing SKILL.md files: via the SkillToolset constructor and using the `discover_from_paths` function. ```python from pathlib import Path from haiku.skills import SkillToolset from haiku.skills.discovery import discover_from_paths # Method 1: Via SkillToolset constructor toolset = SkillToolset(skill_paths=[ Path("./skills"), # Parent directory - discovers all subdirectories Path("./custom-skill"), # Direct skill directory with SKILL.md ]) # Method 2: Direct discovery with error handling skills, errors = discover_from_paths([Path("./skills")]) for skill in skills: print(f"Loaded: {skill.metadata.name} - {skill.metadata.description}") for error in errors: print(f"Error in {error.path}: {error}") ``` -------------------------------- ### Integrate MCP Servers as Skills Source: https://context7.com/ggozad/haiku.skills/llms.txt Shows how to wrap various Model Context Protocol (MCP) server types (Stdio, SSE, HTTP) into Haiku skills and incorporate them into an agent toolset. ```python from pydantic_ai.mcp import MCPServerStdio, MCPServerSSE, MCPServerStreamableHTTP from haiku.skills import skill_from_mcp, SkillToolset stdio_skill = skill_from_mcp( MCPServerStdio("uvx", args=["my-mcp-server"]), name="my-mcp-skill", description="Tools from my MCP server.", instructions="Use these tools when the user asks about data processing." ) toolset = SkillToolset(skills=[stdio_skill]) ``` -------------------------------- ### Define and Use a Skill Programmatically Source: https://context7.com/ggozad/haiku.skills/llms.txt Shows how to define a Skill class with metadata, tools (including stateful ones), and state management, then integrate it into a SkillToolset. ```python from pydantic import BaseModel from pydantic_ai import RunContext from haiku.skills import Skill, SkillMetadata, SkillSource, SkillToolset, build_system_prompt from haiku.skills.state import SkillRunDeps # Define a state model for the skill class CalculatorState(BaseModel): history: list[str] = [] # Create a tool function with state access def add(ctx: RunContext[SkillRunDeps], a: float, b: float) -> float: """Add two numbers.""" result = a + b if ctx.deps and ctx.deps.state and isinstance(ctx.deps.state, CalculatorState): ctx.deps.state.history.append(f"{a} + {b} = {result}") return result def multiply(a: float, b: float) -> float: """Multiply two numbers.""" return a * b # Create the skill programmatically skill = Skill( metadata=SkillMetadata( name="calculator", description="Perform mathematical calculations with history tracking.", ), source=SkillSource.ENTRYPOINT, instructions="Use the add and multiply tools to perform calculations.", tools=[add, multiply], state_type=CalculatorState, state_namespace="calculator", ) # Use the skill toolset = SkillToolset(skills=[skill]) print(toolset.skill_catalog) # Output: - **calculator**: Perform mathematical calculations with history tracking. ``` -------------------------------- ### Declare Python Entrypoint for Haiku Skill (TOML) Source: https://github.com/ggozad/haiku.skills/blob/main/docs/skill-sources.md Illustrates how to expose a Python skill through package entrypoints by defining it in the `pyproject.toml` file under the `haiku.skills` group. This enables automatic discovery by Haiku. ```toml [project.entry-points."haiku.skills"] my-skill = "my_package.skills:create_my_skill" ``` -------------------------------- ### Build Skill-Aware System Prompt Source: https://context7.com/ggozad/haiku.skills/llms.txt Generate a system prompt for the main agent that includes available skills and custom preamble. This function helps tailor the agent's behavior and context based on its capabilities. ```python from haiku.skills import SkillToolset, build_system_prompt toolset = SkillToolset(skill_paths=[Path("./skills")]) # Default preamble prompt = build_system_prompt(toolset.skill_catalog) # Custom preamble prompt = build_system_prompt( toolset.skill_catalog, preamble="You are an expert data analyst with access to specialized skills.", ) print(prompt) # Output: # You are an expert data analyst with access to specialized skills. # # ## Available skills # # - **web**: Search the web and fetch page content. # - **code-execution**: Write and execute Python code to solve tasks. # # ## Instructions # ... ``` -------------------------------- ### Implement in-process Python tools Source: https://github.com/ggozad/haiku.skills/blob/main/docs/skills.md Demonstrates how to define a Python function as a tool and register it within a SkillToolset for use by a pydantic-ai agent. ```python from haiku.skills import Skill, SkillMetadata, SkillSource, SkillToolset, build_system_prompt from pydantic_ai import Agent def add(a: float, b: float) -> float: """Add two numbers.""" return a + b skill = Skill( metadata=SkillMetadata( name="calculator", description="Perform mathematical calculations.", ), source=SkillSource.ENTRYPOINT, instructions="Use the add tool to add numbers.", tools=[add], ) toolset = SkillToolset(skills=[skill]) agent = Agent( "anthropic:claude-sonnet-4-5-20250929", instructions=build_system_prompt(toolset.skill_catalog), toolsets=[toolset], ) ``` -------------------------------- ### Convert Python Scripts to Tools Source: https://context7.com/ggozad/haiku.skills/llms.txt Explains how to define standalone Python scripts with metadata for automatic discovery and conversion into typed tools via AST parsing. ```python # /// script # dependencies = ["pandas"] # /// """Analyze data using pandas.""" import sys import pandas as pd def main(data: str, operation: str = "describe") -> str: """Analyze the given data.""" df = pd.read_csv(pd.io.common.StringIO(data)) return df.describe().to_string() if operation == "describe" else str(df.info()) if __name__ == "__main__": print(main(sys.argv[1], sys.argv[2])) ``` ```python from pathlib import Path from haiku.skills.script_tools import discover_script_tools tools = discover_script_tools(Path("./skills/my-skill")) for tool in tools: print(f"Tool: {tool.name}") ``` -------------------------------- ### Wrap MCP Stdio Server as a Haiku Skill (Python) Source: https://github.com/ggozad/haiku.skills/blob/main/docs/skill-sources.md Shows how to integrate an MCP server communicating via standard input/output (stdio) as a Haiku skill. The `skill_from_mcp` function adapts the MCP server's tools for use within Haiku. ```python from pydantic_ai.mcp import MCPServerStdio from haiku.skills import skill_from_mcp skill = skill_from_mcp( MCPServerStdio("uvx", args=["my-mcp-server"]), name="my-mcp-skill", description="Tools from my MCP server.", instructions="Use these tools when the user asks about...", ) ``` -------------------------------- ### Implement Custom Skills with State Source: https://context7.com/ggozad/haiku.skills/llms.txt Shows how to define a custom skill with internal state using Pydantic models, integrate MCP servers, and execute streaming runs with AG-UI. ```python import asyncio from pathlib import Path from pydantic import BaseModel from pydantic_ai import Agent, RunContext from haiku.skills import Skill, SkillToolset, build_system_prompt, run_agui_stream, skill_from_mcp from haiku.skills.state import SkillRunDeps from pydantic_ai.mcp import MCPServerStdio class NotesState(BaseModel): notes: list[str] = [] def add_note(ctx: RunContext[SkillRunDeps], content: str) -> str: if ctx.deps and ctx.deps.state and isinstance(ctx.deps.state, NotesState): ctx.deps.state.notes.append(content) return f"Added note #{len(ctx.deps.state.notes)}" return "Note added" notes_skill = Skill( metadata=SkillMetadata(name="notes", description="Take and manage notes."), source=SkillSource.ENTRYPOINT, tools=[add_note], state_type=NotesState, state_namespace="notes", ) toolset = SkillToolset(skills=[notes_skill]) agent = Agent("anthropic:claude-sonnet-4-5-20250929", toolsets=[toolset]) ``` -------------------------------- ### Wrap MCP SSE Server as a Haiku Skill (Python) Source: https://github.com/ggozad/haiku.skills/blob/main/docs/skill-sources.md Demonstrates integrating an MCP server that uses Server-Sent Events (SSE) as a Haiku skill. The `skill_from_mcp` function facilitates this integration, making SSE-based tools accessible. ```python from pydantic_ai.mcp import MCPServerSSE from haiku.skills import skill_from_mcp skill = skill_from_mcp( MCPServerSSE("http://localhost:8080/sse"), name="sse-skill", description="Tools via SSE.", ) ``` -------------------------------- ### Manage State Snapshots and Schemas Source: https://github.com/ggozad/haiku.skills/blob/main/docs/ag-ui.md Shows how to interact with the SkillToolset to capture, restore, and retrieve state snapshots and JSON schemas for registered skills. ```python from haiku.skills import SkillToolset toolset = SkillToolset(skills=[skill]) # Get a snapshot of all namespaced state toolset.build_state_snapshot() # {"my-skill": {"items": []}} # Restore from a snapshot toolset.restore_state_snapshot({"my-skill": {"items": ["hello"]}}) # Get a specific namespace toolset.get_namespace("my-skill") # MyState(items=["hello"]) # Schema information toolset.state_schemas # {"my-skill": } ``` -------------------------------- ### Override Entrypoint Skill with Custom Configuration (Python) Source: https://github.com/ggozad/haiku.skills/blob/main/docs/skill-sources.md Illustrates how to prioritize a manually defined skill over an identically named entrypoint-discovered skill. By passing the custom skill directly to `SkillToolset`, it takes precedence. ```python from haiku.skills import SkillToolset # Assume create_my_skill is defined elsewhere # def create_my_skill(db_path: str) -> Skill: # ... custom_skill = create_my_skill(db_path="/custom/path") toolset = SkillToolset( skills=[custom_skill], use_entrypoints=True, # entrypoint for "my-skill" is skipped ) ``` -------------------------------- ### Configure Haiku Skills Environment Variables Source: https://context7.com/ggozad/haiku.skills/llms.txt Sets the required environment variables to define model selection for agents and sub-agents, as well as paths for skill discovery. ```bash export HAIKU_SKILLS_MODEL="openai:gpt-4o" export HAIKU_SKILL_MODEL="ollama:llama3" export HAIKU_SKILLS_PATHS="./skills:./more-skills" export HAIKU_SKILLS_USE_ENTRYPOINTS="true" ``` -------------------------------- ### Define and use skill state with Pydantic Source: https://github.com/ggozad/haiku.skills/blob/main/docs/skills.md Demonstrates how to define a Pydantic model for skill state, inject it into tool functions via RunContext, and track it within a SkillToolset. The state is automatically managed and can be exported as a snapshot. ```python from pydantic import BaseModel from pydantic_ai import RunContext from haiku.skills import Skill, SkillMetadata, SkillSource, SkillToolset from haiku.skills.state import SkillRunDeps class CalculatorState(BaseModel): history: list[str] = [] def add(ctx: RunContext[SkillRunDeps], a: float, b: float) -> float: """Add two numbers.""" result = a + b if ctx.deps and ctx.deps.state and isinstance(ctx.deps.state, CalculatorState): ctx.deps.state.history.append(f"{a} + {b} = {result}") return result skill = Skill( metadata=SkillMetadata( name="calculator", description="Perform mathematical calculations.", ), source=SkillSource.ENTRYPOINT, instructions="Use the add tool to add numbers.", tools=[add], state_type=CalculatorState, state_namespace="calculator", ) toolset = SkillToolset(skills=[skill]) # State is accessible via the toolset print(toolset.build_state_snapshot()) ``` -------------------------------- ### Create a Skill from a Python Entrypoint (Python) Source: https://github.com/ggozad/haiku.skills/blob/main/docs/skill-sources.md Defines a callable function that returns a `Skill` object, intended to be used as a Python entrypoint for Haiku. This function sets up the skill's metadata and source. ```python from haiku.skills import Skill, SkillMetadata, SkillSource def create_my_skill() -> Skill: return Skill( metadata=SkillMetadata(name="my-skill", description="Data analysis."), source=SkillSource.ENTRYPOINT, instructions="# My Skill\n\nInstructions here...", ) ``` -------------------------------- ### Wrap MCP Streamable HTTP Server as a Haiku Skill (Python) Source: https://github.com/ggozad/haiku.skills/blob/main/docs/skill-sources.md Explains how to integrate an MCP server communicating via streamable HTTP as a Haiku skill. `skill_from_mcp` handles the adaptation, allowing Haiku to utilize tools exposed through this protocol. ```python from pydantic_ai.mcp import MCPServerStreamableHTTP from haiku.skills import skill_from_mcp skill = skill_from_mcp( MCPServerStreamableHTTP("http://localhost:8080/mcp"), name="http-skill", description="Tools via streamable HTTP.", ) ``` -------------------------------- ### Perform sibling imports in scripts Source: https://github.com/ggozad/haiku.skills/blob/main/docs/skills.md Demonstrates how scripts within the scripts/ directory can perform package-style sibling imports. ```python # scripts/utils.py def helper(): return "shared logic" # scripts/main_script.py from scripts.utils import helper ``` -------------------------------- ### Define Skill State with Pydantic Source: https://github.com/ggozad/haiku.skills/blob/main/docs/ag-ui.md Demonstrates how to define a state model using Pydantic and register it within a Skill object. This state is tracked per namespace and accessible during skill execution. ```python from pydantic import BaseModel from haiku.skills import Skill, SkillMetadata, SkillSource class MyState(BaseModel): items: list[str] = [] skill = Skill( metadata=SkillMetadata(name="my-skill", description="..."), source=SkillSource.ENTRYPOINT, instructions="...", state_type=MyState, state_namespace="my-skill", ) ``` -------------------------------- ### Introspect skill state configuration Source: https://github.com/ggozad/haiku.skills/blob/main/docs/skills.md Shows how to retrieve the state metadata and JSON schema for a skill without executing it, using the state_metadata method. ```python meta = skill.state_metadata() # StateMetadata(namespace="calculator", type=, schema={...}) ``` -------------------------------- ### Define Custom Dependency Dataclass Source: https://github.com/ggozad/haiku.skills/blob/main/docs/ag-ui.md Shows how to implement a custom dependency class that satisfies the StateHandler protocol by including a state dictionary. This allows developers to combine state management with other application-specific dependencies like database connections. ```python from dataclasses import dataclass, field from typing import Any @dataclass class MyDeps: state: dict[str, Any] = field(default_factory=dict) db: MyDatabase = ... ``` -------------------------------- ### Haiku Skills CLI Commands Source: https://context7.com/ggozad/haiku.skills/llms.txt Manage and test skills using the Haiku Skills command-line interface. Commands include validating skill directories, listing discovered skills, and launching an interactive chat TUI. ```bash # Validate skill directories against the Agent Skills specification haiku-skills validate ./skills/web ./skills/calculator # Output: VALID or INVALID with error details # List discovered skills haiku-skills list -s ./skills haiku-skills list --use-entrypoints haiku-skills list -s ./skills --use-entrypoints # Interactive chat TUI (requires [tui] extra) haiku-skills chat -s ./skills -m openai:gpt-4o # Chat with entrypoints and skill filtering haiku-skills chat --use-entrypoints -k web -k code-execution -m openai:gpt-4o # Specify model for skill sub-agents haiku-skills chat -s ./skills -m openai:gpt-4o --skill-model ollama:llama3 ``` -------------------------------- ### POST /chat Source: https://context7.com/ggozad/haiku.skills/llms.txt Streams real-time sub-agent tool calls and agent responses using the AG-UI protocol. ```APIDOC ## POST /chat ### Description Initiates a streaming chat session where the agent processes user input and streams back real-time events, including sub-agent tool calls and content updates. ### Method POST ### Endpoint /chat ### Request Body - **message** (string) - Required - The user input message to process. ### Request Example { "message": "Search for the latest news on AI." } ### Response #### Success Response (200) - **text/event-stream** (stream) - A stream of encoded events containing agent activity and content. #### Response Example { "event": "tool_call", "content": "web_search(query='latest AI news')" } ``` -------------------------------- ### SkillRegistry for Skill Management Source: https://context7.com/ggozad/haiku.skills/llms.txt Utilize the SkillRegistry for discovering, loading, and looking up skills. It supports manual registration, discovery from paths and entrypoints, and provides methods to access skill information. ```python from pathlib import Path from haiku.skills import Skill, SkillMetadata, SkillSource from haiku.skills.registry import SkillRegistry registry = SkillRegistry() # Register a skill manually skill = Skill( metadata=SkillMetadata(name="custom", description="Custom skill."), source=SkillSource.ENTRYPOINT, instructions="Instructions here.", ) registry.register(skill) # Discover from paths with error handling errors = registry.discover(paths=[Path("./skills")]) for error in errors: print(f"Warning: {error}") # Discover from entrypoints registry.discover(use_entrypoints=True) # Access skills print(registry.names) # ['custom', 'web', ...] skill = registry.get("web") # Get skill by name metadata_list = registry.list_metadata() # Get all skill metadata ``` -------------------------------- ### Skill Registry API Source: https://context7.com/ggozad/haiku.skills/llms.txt Interface for discovering, registering, and retrieving skill metadata within the Haiku environment. ```APIDOC ## SkillRegistry ### Description Manages the lifecycle of skills, including discovery from file paths or entrypoints and metadata retrieval. ### Methods - **register(skill)**: Manually adds a skill to the registry. - **discover(paths, use_entrypoints)**: Scans for skills and returns any validation errors. - **get(name)**: Retrieves a specific skill by name. - **list_metadata()**: Returns metadata for all registered skills. ### Response #### Success Response (200) - **SkillMetadata** (object) - Metadata object containing name, description, and source information. ``` -------------------------------- ### Manage Per-Skill Persistent State Source: https://context7.com/ggozad/haiku.skills/llms.txt Demonstrates defining a Pydantic state model for a skill to persist data across tool calls and managing state snapshots within a toolset. ```python from pydantic import BaseModel from haiku.skills import Skill, SkillToolset class SearchState(BaseModel): queries: list[str] = [] results_count: int = 0 skill = Skill( metadata=SkillMetadata(name="search", description="Search with history."), state_type=SearchState, state_namespace="search", tools=[search] ) toolset = SkillToolset(skills=[skill]) toolset.restore_state_snapshot({"search": {"queries": ["python"], "results_count": 10}}) ``` -------------------------------- ### Validate skill directory Source: https://github.com/ggozad/haiku.skills/blob/main/docs/skills.md Uses the haiku-skills CLI tool to validate a skill directory against the Agent Skills specification. ```bash haiku-skills validate ./my-skill ``` -------------------------------- ### Define SKILL.md metadata Source: https://github.com/ggozad/haiku.skills/blob/main/docs/skills.md Defines the structure of a SKILL.md file using YAML frontmatter for metadata and markdown for instructions. This file is required for every skill defined in the Haiku framework. ```markdown --- name: my-skill description: A brief description of what the skill does. --- # My Skill Detailed instructions for the sub-agent go here. This content becomes the system prompt when the skill is executed. ``` -------------------------------- ### Model Resolution API Source: https://context7.com/ggozad/haiku.skills/llms.txt Utility to resolve model strings into pydantic-ai Model instances, supporting providers like OpenAI, Anthropic, and Ollama. ```APIDOC ## resolve_model ### Description Converts a model identifier string into a usable model instance. Supports local Ollama instances via environment variables. ### Parameters #### Query Parameters - **model_string** (string) - Required - The model identifier (e.g., 'openai:gpt-4o', 'ollama:llama3'). ### Request Example resolve_model("ollama:llama3") ### Response #### Success Response (200) - **ModelInstance** (object) - A configured pydantic-ai Model instance. ```