Building AI agents, atomically
feat(skills): add atomic create-* skills and reference them from framework + new-app
KennyVaneetvelde5867c910478a
diff --git a/claude-plugin/atomic-agents/.claude-plugin/plugin.json b/claude-plugin/atomic-agents/.claude-plugin/plugin.jsonindex af3b21a..d432394 100644--- a/claude-plugin/atomic-agents/.claude-plugin/plugin.json+++ b/claude-plugin/atomic-agents/.claude-plugin/plugin.json@@ -1,7 +1,7 @@{"name": "atomic-agents",- "version": "2.0.1",- "description": "Skills plus explorer and reviewer subagents for building, scaffolding, understanding, and auditing applications with the Atomic Agents Python framework. Progressive-disclosure reference material for schemas, agents, tools, context providers, prompts, orchestration, memory, hooks, providers, project structure, and testing — plus isolated-context subagents for codebase mapping and code review, and a new-app scaffolder.",+ "version": "2.1.0",+ "description": "Skills plus explorer and reviewer subagents for building, scaffolding, understanding, and auditing applications with the Atomic Agents Python framework. Includes the umbrella `framework` skill, action-oriented `create-atomic-schema` / `create-atomic-agent` / `create-atomic-tool` / `create-atomic-context-provider` skills, the `new-app` scaffolder, progressive-disclosure reference material for prompts, orchestration, memory, hooks, providers, project structure, and testing, and isolated-context subagents for codebase mapping and code review.","author": {"name": "BrainBlend AI","email": "[email protected]"diff --git a/claude-plugin/atomic-agents/skills/create-atomic-agent/SKILL.md b/claude-plugin/atomic-agents/skills/create-atomic-agent/SKILL.mdnew file mode 100644index 0000000..36634fe--- /dev/null+++ b/claude-plugin/atomic-agents/skills/create-atomic-agent/SKILL.md@@ -0,0 +1,160 @@+---+name: create-atomic-agent+description: Build and wire an `AtomicAgent[InSchema, OutSchema]` — schemas, `AgentConfig`, `SystemPromptGenerator`, provider client, history, hooks, optional context providers. Use when the user asks to "create an agent", "add another agent", "build an `AtomicAgent`", "wire up an agent", "make a planner/router/extractor agent", or runs `/atomic-agents:create-atomic-agent`.+---++# Create an Atomic Agent++An agent is an LLM-backed transformer from one `BaseIOSchema` to another. Building one means: design the schemas, write the system prompt, wire the provider client, build the `AgentConfig`, instantiate `AtomicAgent[In, Out]`.++For deep material (streaming, token counting, hooks, multi-agent memory), the authority is `../framework/references/agents.md` plus `providers.md`, `prompts.md`, and `memory.md`. This skill is the action-oriented path: clarify → write → run.++## When this fires vs the umbrella `framework` skill++- **This skill**: the user is creating or wiring a specific agent — "add a planner agent", "build a Q&A agent", "make a router that classifies tickets".+- **`framework` skill**: questions about Atomic Agents in general, or the user is doing something other than authoring an agent.++## Phase 1 — Clarify++Bundle into one message:++1. **What should the agent do?** One sentence. Becomes the persona / `background` line.+2. **Inputs and outputs.** Use `BasicChatInputSchema` / `BasicChatOutputSchema` for free-form chat. Use a custom pair for anything structured (extraction, classification, planning, routing). When custom, branch to the `create-atomic-schema` skill for the schema authoring.+3. **Provider.** OpenAI / Anthropic / Groq / Ollama / Gemini / OpenRouter / MiniMax. Default: whatever the project already uses; otherwise OpenAI.+4. **Conversational?** Yes → wire a `ChatHistory`. No (single-shot transformer) → omit it for stateless behavior.+5. **Context providers.** Anything to inject into the prompt at runtime (current time, user identity, retrieved docs)? If yes, plan to also use the `create-atomic-context-provider` skill afterwards.++Skip anything already settled in context.++## Phase 2 — Plan++State the plan in one short block:++- File: `<project>/agents/<agent_name>.py` (or directly in `main.py` for a tiny project — see `../framework/references/project-structure.md`).+- Schemas: which pair, where they live.+- Provider + model + Instructor mode. Default models: OpenAI `gpt-5-mini`, Anthropic `claude-haiku-4-5`, Groq `llama-3.3-70b-versatile`, Ollama `llama3.1`, Gemini `gemini-2.5-flash`.+- `SystemPromptGenerator` content — three sections: `background`, `steps`, `output_instructions`.+- History? Hooks? Context providers?++## Phase 3 — Implement++### Canonical imports (do not deviate)++```python+from atomic_agents import (+ AtomicAgent, AgentConfig,+ BasicChatInputSchema, BasicChatOutputSchema,+)+from atomic_agents.context import ChatHistory, SystemPromptGenerator+from instructor import Mode+```++### Wire the provider client (always Instructor-wrapped)++The full per-provider matrix lives in `../framework/references/providers.md`. Quick recap:++```python+# OpenAI — default mode is Mode.TOOLS+import os, instructor, openai+client = instructor.from_openai(openai.OpenAI(api_key=os.environ["OPENAI_API_KEY"]))+model = "gpt-5-mini"+api_params: dict = {}++# Anthropic — Mode.TOOLS, max_tokens REQUIRED in model_api_parameters+import anthropic+client = instructor.from_anthropic(anthropic.Anthropic(api_key=os.environ["ANTHROPIC_API_KEY"]))+model = "claude-haiku-4-5"+api_params = {"max_tokens": 4096}++# Gemini — Mode.GENAI_TOOLS, assistant_role="model"+from google import genai+client = instructor.from_genai(genai.Client(api_key=os.environ["GEMINI_API_KEY"]), mode=Mode.GENAI_TOOLS)+model = "gemini-2.5-flash"+api_params = {}++# Groq / Ollama / MiniMax — Mode.JSON in both factory and AgentConfig+```++### Build the agent++```python+from atomic_agents import AtomicAgent, AgentConfig+from atomic_agents.context import ChatHistory, SystemPromptGenerator++agent = AtomicAgent[MyInput, MyOutput](+ config=AgentConfig(+ client=client,+ model=model,+ history=ChatHistory(), # omit for stateless+ system_prompt_generator=SystemPromptGenerator(+ background=["You are a concise research assistant."],+ steps=[+ "Read the question carefully.",+ "Decide what minimum information answers it.",+ "Produce the answer in the required schema.",+ ],+ output_instructions=[+ "Reply under 100 words.",+ "If unsure, set status='error' and explain why.",+ ],+ ),+ # Provider-specific knobs — match the Instructor factory+ # mode=Mode.TOOLS, # OpenAI / Anthropic / OpenRouter+ # mode=Mode.JSON, # Groq / Ollama / MiniMax+ # mode=Mode.GENAI_TOOLS, assistant_role="model", # Gemini+ model_api_parameters=api_params or {"temperature": 0.2},+ )+)+```++### Generics carry the truth++`AtomicAgent[MyInput, MyOutput]` — write the type parameters explicitly. The framework reads them at class-definition time. Do **not** rely on subclass-level `input_schema` / `output_schema` class attributes.++### Provider-specific knobs (most common gotchas)++- **Anthropic** without `max_tokens` in `model_api_parameters` → API rejects every call.+- **Gemini** without `assistant_role="model"` → role mismatch on every turn.+- **Groq / Ollama / MiniMax** with `Mode.TOOLS` → tools formatted in a way the provider does not accept; flip to `Mode.JSON`.+- Reasoning models (o-series, GPT-5 reasoning variants) → often want `system_role=None` and `reasoning_effort` in `model_api_parameters`.++## Phase 4 — Run and verify++```python+out = agent.run(MyInput(...))+print(out)+```++Quick smoke test without paying for a real call:++```bash+uv run python -c "from <project>.agents.<agent_name> import agent; print(type(agent).__name__, '->', agent.input_schema.__name__, '/', agent.output_schema.__name__)"+```++If output validation fails repeatedly, the `parse:error` hook has the details — see `../framework/references/hooks.md` for registration.++## Phase 5 — Hand off++Tell the user:++- How to call `agent.run(...)` (and `run_async`, `run_stream`, `run_async_stream` when appropriate).+- Which env var to set for the provider key.+- Optional next steps:+ - Tools the agent should be able to invoke → `create-atomic-tool` skill.+ - Dynamic data injected into the prompt → `create-atomic-context-provider` skill.+ - Custom schemas → `create-atomic-schema` skill.+ - Multiple agents working together → `../framework/references/orchestration.md`.+ - Telemetry / retries / logging → `../framework/references/hooks.md`.+ - Conversation persistence, summarization, multi-agent memory → `../framework/references/memory.md`.++## Anti-patterns++- Forgetting to wrap the client with `instructor.from_*` — structured outputs silently stop working.+- `BaseModel` instead of `BaseIOSchema` for the agent's input or output type.+- `AgentConfig.mode` out of sync with the Instructor factory mode.+- `assistant_role="assistant"` on Gemini — must be `"model"`.+- Missing `max_tokens` on Anthropic — every call fails.+- Hardcoded API keys in the source — read from env.+- Unbounded `ChatHistory` in a long-running service — monitor `agent.get_context_token_count().utilization` or set `max_messages`.++For deep material — streaming, async, token counting, hooks, multi-agent history — load `../framework/references/agents.md`.diff --git a/claude-plugin/atomic-agents/skills/create-atomic-context-provider/SKILL.md b/claude-plugin/atomic-agents/skills/create-atomic-context-provider/SKILL.mdnew file mode 100644index 0000000..443cad6--- /dev/null+++ b/claude-plugin/atomic-agents/skills/create-atomic-context-provider/SKILL.md@@ -0,0 +1,207 @@+---+name: create-atomic-context-provider+description: Build a `BaseDynamicContextProvider` that injects a named, titled block into an agent's system prompt at every `run()` — current time, user identity, retrieved RAG docs, session state, cached DB schema. Use when the user asks to "add a context provider", "inject X into the prompt", "give the agent dynamic context", "wire up RAG", "make a `BaseDynamicContextProvider`", or runs `/atomic-agents:create-atomic-context-provider`.+---++# Create an Atomic Agents Context Provider++A context provider injects a named, titled block into the agent's system prompt at every `run()`. The base prompt stays static; the context is what changes between calls.++For deep material (caching strategies, async data sources, multi-agent sharing patterns), the authority is `../framework/references/context-providers.md`. This skill is the action-oriented path: clarify → write → register.++## When this fires vs the umbrella `framework` skill++- **This skill**: the user wants to add a provider — "inject the user's name", "make the agent see the current time", "feed retrieved docs into the prompt", "share session state across two agents".+- **`framework` skill**: questions about Atomic Agents in general, or about something other than authoring a provider.++## Phase 1 — Clarify++Bundle into one message:++1. **What goes into the prompt?** One sentence. Defines the provider's job.+2. **Where does the data come from?** In-memory state mutated by your code? A vector DB lookup? A REST call? A clock?+3. **How fresh must it be?** Per-`run()` (default), every N seconds (cache), or refreshed externally before each call (async data).+4. **Which agent(s)?** One agent, or shared across multiple agents?++Skip what's already obvious from context.++## Phase 2 — Plan++Confirm in one short block:++- File: `<project>/context_providers.py` (or alongside the agent that owns it).+- Class: `<Topic>Ctx(BaseDynamicContextProvider)`.+- Title (rendered as the section header in the prompt) — must be unique across providers on the same agent.+- Update mechanism: mutate fields between `run()` calls (most common), set via a method, or `await refresh()` for async sources.++## Phase 3 — Implement++### Skeleton++```python+from atomic_agents.context import BaseDynamicContextProvider+++class UserCtx(BaseDynamicContextProvider):+ def __init__(self):+ super().__init__(title="User Context")+ self.name: str = ""+ self.role: str = ""++ def get_info(self) -> str:+ if not self.name:+ return "No user is logged in."+ return f"User: {self.name} (role: {self.role})"+```++`get_info()` is **synchronous** and runs on **every** `agent.run()` — keep it cheap. No HTTP, no DB queries, no file I/O. Cache slow sources (see "Cached" pattern below). For async data sources, `await provider.refresh()` from your loop before calling the agent.++### Common patterns++**Time** — read-only, no state mutation needed:++```python+from datetime import datetime, timezone++class TimeCtx(BaseDynamicContextProvider):+ def __init__(self):+ super().__init__(title="Current Time")++ def get_info(self) -> str:+ return datetime.now(timezone.utc).isoformat()+```++**RAG / retrieved docs** — set externally, read inside `get_info()`:++```python+class RAGCtx(BaseDynamicContextProvider):+ def __init__(self):+ super().__init__(title="Retrieved Documents")+ self.docs: list[dict] = []++ def set(self, docs: list[dict]) -> None:+ self.docs = docs++ def get_info(self) -> str:+ if not self.docs:+ return "No relevant documents retrieved."+ return "\n\n".join(f"[{d['source']}] {d['content']}" for d in self.docs)++# In the calling code, just before agent.run():+rag.set(vector_db.search(query, k=4))+agent.run(query_input)+```++**Session** — mutable key/value state shared across agents:++```python+class SessionCtx(BaseDynamicContextProvider):+ def __init__(self):+ super().__init__(title="Session")+ self._data: dict[str, str] = {}++ def set(self, key: str, value: str) -> None:+ self._data[key] = value++ def get_info(self) -> str:+ if not self._data:+ return "No session state."+ return "\n".join(f"- {k}: {v}" for k, v in self._data.items())+```++**Cached** — for slow sources (DB schema, expensive computation):++```python+import time++class DBSchemaCtx(BaseDynamicContextProvider):+ def __init__(self, conn, ttl_seconds: int = 300):+ super().__init__(title="Database Schema")+ self._conn = conn+ self._ttl = ttl_seconds+ self._cached: str = ""+ self._at: float = 0.0++ def get_info(self) -> str:+ now = time.time()+ if not self._cached or now - self._at > self._ttl:+ self._cached = render_schema(self._conn)+ self._at = now+ return self._cached+```++**Async source** — refresh outside, read sync inside:++```python+class AsyncCtx(BaseDynamicContextProvider):+ def __init__(self):+ super().__init__(title="Async Data")+ self._cached = ""++ async def refresh(self) -> None:+ self._cached = format(await fetch_remote())++ def get_info(self) -> str:+ return self._cached++# Caller+await ctx.refresh()+await agent.run_async(input_data)+```++## Phase 4 — Register++```python+ctx = UserCtx()+agent.register_context_provider("user", ctx)++# Mutate before each run as needed:+ctx.name = "Alice"; ctx.role = "admin"+agent.run(...)+```++Sharing one provider instance across agents is allowed — updates propagate to every agent that registered it:++```python+shared = SessionCtx()+agent_a.register_context_provider("session", shared)+agent_b.register_context_provider("session", shared)+shared.set("locale", "en-GB") # visible to both agents+```++Inspect or unregister:++```python+"user" in agent.context_providers+agent.unregister_context_provider("user")+```++## Phase 5 — Verify++Quick smoke test that the provider renders:++```bash+uv run python -c "from <project>.context_providers import UserCtx; c = UserCtx(); c.name='Alice'; c.role='admin'; print(c.get_info())"+```++Then confirm the rendered system prompt includes the provider's section by inspecting `agent.system_prompt_generator.generate_prompt(...)` or by running the agent and checking the first request's payload via the `completion:kwargs` hook (see `../framework/references/hooks.md`).++## Phase 6 — Hand off++Tell the user:++- Where the provider lives, what name was used in `register_context_provider`, and how to mutate it.+- The lifecycle: register once, mutate fields between calls, the prompt picks up the change automatically.+- Optional next steps:+ - The agent that consumes it → `create-atomic-agent` skill.+ - A research / RAG loop that updates the provider in a loop → see `atomic-examples/deep-research/` and `../framework/references/orchestration.md`.++## Anti-patterns++- Slow I/O inside `get_info()` — runs on every `agent.run()`. Cache it or refresh externally.+- Returning a non-string from `get_info()` — raises at prompt time.+- Forgetting `register_context_provider(...)` — the provider never reaches the prompt.+- Duplicate titles across providers on the same agent — sections collide. Use unique titles.+- Storing secrets in the provider — they end up in every LLM request. Inject only what the model needs to reason about.++For deeper material — multi-agent sharing patterns, dynamic-update research loops, async source patterns — load `../framework/references/context-providers.md`.diff --git a/claude-plugin/atomic-agents/skills/create-atomic-schema/SKILL.md b/claude-plugin/atomic-agents/skills/create-atomic-schema/SKILL.mdnew file mode 100644index 0000000..fa29105--- /dev/null+++ b/claude-plugin/atomic-agents/skills/create-atomic-schema/SKILL.md@@ -0,0 +1,137 @@+---+name: create-atomic-schema+description: Design and write a `BaseIOSchema` input/output pair for an Atomic Agents agent or tool — docstrings, field descriptions, validators, error variants. Use when the user asks to "create a schema", "design the input/output schema", "define an `IOSchema`", "write a `BaseIOSchema`", "model the agent's output", or runs `/atomic-agents:create-atomic-schema`.+---++# Create an Atomic Agents Schema++Author a `BaseIOSchema` pair (input and/or output) that becomes the contract between an agent or tool and its caller. The framework enforces docstrings on every subclass, and Instructor flows field descriptions into the LLM prompt — so the schema **is** part of the prompt, not just typing.++For deep material (validators, discriminated unions, error envelopes), the authority is `../framework/references/schemas.md`. This skill is the action-oriented path: clarify → write → validate.++## When this fires vs the umbrella `framework` skill++- **This skill**: the user is creating or modifying a specific schema — e.g. "design the output schema for the planner agent", "add a field to `WeatherInput`", "split the result into success and failure variants".+- **`framework` skill**: the user is asking about Atomic Agents in general or doing something other than authoring schemas.++## Phase 1 — Clarify++Ask only what is not already obvious from context. Bundle into one message; do not interrogate one-at-a-time.++1. **Caller** — is this for an `AtomicAgent`, a `BaseTool`, both (an agent that emits a tool-input schema), or a nested sub-schema?+2. **Direction** — input only, output only, or a paired Input/Output?+3. **Fields** — what fields does the caller need, with which types? (Required vs optional, defaults, constraints.)+4. **Failure modes** — can this legitimately fail? If yes, plan a typed error variant rather than raising. See `../framework/references/schemas.md` → "Error-schema pattern".++If the user is mid-conversation about an existing schema, skip questions answered in context.++## Phase 2 — Write++Place schema(s) where they will be imported from. Conventional locations:++- `<project>/agents/<agent_name>/schemas.py` — agent-owned schemas+- `<project>/tools/<tool_name>_tool.py` — tool I/O lives next to the tool+- `<project>/schemas/<topic>.py` — schemas shared across multiple components++### Required ingredients on every schema++- Subclass `BaseIOSchema` (not `BaseModel`).+- A non-empty class docstring — the framework raises at import otherwise. Write it for the LLM, because Instructor uses it as the schema's `description`.+- Every `Field(...)` carries a `description=` written for the LLM.+- Use `Literal[...]` for closed sets before reaching for `Enum` — flatter JSON Schema, easier for Instructor.++### Minimal template++```python+from typing import Optional, Literal+from pydantic import Field+from atomic_agents import BaseIOSchema+++class WeatherInput(BaseIOSchema):+ """A request for current weather conditions."""++ city: str = Field(..., description="City name, e.g. 'Brussels' or 'New York'.")+ units: Literal["metric", "imperial"] = Field(+ default="metric",+ description="Unit system for the temperature.",+ )+++class WeatherOutput(BaseIOSchema):+ """Current weather conditions for a city."""++ status: Literal["ok", "error"] = Field(..., description="Outcome code.")+ temperature_c: Optional[float] = Field(+ default=None, description="Temperature in Celsius when status='ok'."+ )+ summary: Optional[str] = Field(+ default=None, description="Human-readable summary when status='ok'."+ )+ error: Optional[str] = Field(+ default=None, description="Failure message when status='error'."+ )+```++### When to add validators++- **Field-level** for normalization (lowercase, strip, enum coercion) and single-field validation.+- **Model-level** (`@model_validator(mode="after")`) for cross-field rules (start ≤ end, mutually exclusive flags).++Validation errors trigger Instructor retries and fire the `parse:error` hook — they're a feature, not a failure path. Do **not** swallow them.++### When to use discriminated unions++If the caller must exhaustively handle multiple result shapes, prefer a union over an inflated single schema:++```python+class SearchSuccess(BaseIOSchema):+ """Successful search result."""+ kind: Literal["ok"] = "ok"+ results: list[str] = Field(..., description="Matching items.")++class SearchFailure(BaseIOSchema):+ """Search could not complete."""+ kind: Literal["error"] = "error"+ code: Literal["rate_limited", "no_results", "upstream_error"] = Field(+ ..., description="Machine-readable failure code."+ )+ message: str = Field(..., description="Human-readable failure reason.")++class SearchOutput(BaseIOSchema):+ """Search outcome — success or typed failure."""+ result: SearchSuccess | SearchFailure = Field(..., description="Outcome.")+```++The `kind` discriminator on each variant lets Pydantic resolve the union without ambiguity.++## Phase 3 — Verify++Smoke-check the schema imports cleanly and round-trips through `model_json_schema()`:++```bash+uv run python -c "from <project>.<module> import WeatherInput, WeatherOutput; print(WeatherInput.model_json_schema()['title'])"+```++If the import raises `ValueError("… must have a non-empty docstring …")`, add the docstring. If a field's JSON schema is missing a description, add `description=` to its `Field(...)`.++## Phase 4 — Hand off++Tell the user:++- Where the schema lives and what to import.+- Next step in their flow:+ - Wiring it into an agent → `create-atomic-agent` skill.+ - Wiring it into a tool → `create-atomic-tool` skill.+ - Adding a context provider that depends on the same domain → `create-atomic-context-provider` skill.++## Anti-patterns to refuse on sight++- Plain `BaseModel` instead of `BaseIOSchema` — loses docstring enforcement and the JSON-schema overrides Instructor depends on.+- Missing class docstring — framework raises at import.+- `Field(...)` without `description=` — Instructor has nothing to tell the model about the field.+- `Optional[str]` with no default — required-but-nullable, which is rarely the intent.+- `dict`, `Any`, or `object` as a field type — the LLM produces anything and Pydantic cannot validate.+- Catching `ValidationError` to "make the agent more robust" — fix the field constraints or descriptions instead.++For deeper material — composition, nested schemas, discriminated unions in production, validator gotchas — load `../framework/references/schemas.md`.diff --git a/claude-plugin/atomic-agents/skills/create-atomic-tool/SKILL.md b/claude-plugin/atomic-agents/skills/create-atomic-tool/SKILL.mdnew file mode 100644index 0000000..3e6e9ce--- /dev/null+++ b/claude-plugin/atomic-agents/skills/create-atomic-tool/SKILL.md@@ -0,0 +1,200 @@+---+name: create-atomic-tool+description: Build a `BaseTool[InSchema, OutSchema]` subclass — input/output schemas, `BaseToolConfig`, `run()` (and optional `run_async()`), env-driven secrets, typed failure outputs. Use when the user asks to "add a tool", "create a tool", "wrap an API as a tool", "build a `BaseTool`", "make a calculator/search/weather tool", or runs `/atomic-agents:create-atomic-tool`.+---++# Create an Atomic Agents Tool++A tool is a deterministic capability an agent can invoke. In Atomic Agents, every tool is a `BaseTool[InSchema, OutSchema]` subclass with a typed `run()` (and optional `run_async()`). The input/output schemas double as the tool's signature for the LLM and as Pydantic validation at runtime.++For deep material (MCP interop, distributing as a standalone package, advanced error patterns), the authority is `../framework/references/tools.md`. This skill is the action-oriented path: clarify → write → verify.++## When this fires vs the umbrella `framework` skill++- **This skill**: the user is creating a specific tool — wrapping an API, building a calculator, scraping a page, querying a DB.+- **`framework` skill**: questions about Atomic Agents in general, or the user is doing something other than authoring a tool.++## Phase 1 — Clarify++Bundle into one message:++1. **What does the tool do?** One sentence. This becomes the class docstring and feeds the LLM's tool description.+2. **Inputs and outputs.** Names, types, units. If unclear, propose a schema pair and confirm.+3. **External dependencies.** HTTP API? DB? Local computation only? If HTTP, what auth (API key env var, OAuth, none)?+4. **Sync, async, or both?** If the rest of the project is async or the call is I/O bound, plan a `run_async()` alongside `run()`.+5. **Failure modes.** Rate limits, not-found, network errors — how should the agent see them? Default: typed failure output, not raised exceptions.++Skip any question already answered in context.++## Phase 2 — Plan++Confirm the location and shape in one short block, then proceed:++- File: `<project>/tools/<tool_name>_tool.py` (in-project tool — see `../framework/references/project-structure.md`).+- Schemas: `<ToolName>Input`, `<ToolName>Output`, optionally a typed failure shape.+- Config: `<ToolName>Config(BaseToolConfig)` if the tool needs API keys, base URLs, timeouts, retries.+- Sync vs async: pick one or both.+- Error pattern: typed failure output (preferred) vs raise (only for programmer error).++## Phase 3 — Implement++### Skeleton — local computation, no config++```python+from pydantic import Field+from atomic_agents import BaseIOSchema, BaseTool+++class CalculatorInput(BaseIOSchema):+ """Arithmetic expression to evaluate."""+ expression: str = Field(..., description="Python-style arithmetic, e.g. '2 + 2 * 3'.")+++class CalculatorOutput(BaseIOSchema):+ """Result of evaluating the expression."""+ result: float = Field(..., description="Numeric result.")+++class CalculatorTool(BaseTool[CalculatorInput, CalculatorOutput]):+ """Evaluate simple arithmetic expressions safely."""++ def run(self, params: CalculatorInput) -> CalculatorOutput:+ import ast, operator as op+ ops = {ast.Add: op.add, ast.Sub: op.sub, ast.Mult: op.mul, ast.Div: op.truediv}+ def ev(n):+ if isinstance(n, ast.Constant): return n.value+ if isinstance(n, ast.BinOp): return ops[type(n.op)](ev(n.left), ev(n.right))+ raise ValueError("unsupported")+ return CalculatorOutput(result=ev(ast.parse(params.expression, mode="eval").body))+```++### Skeleton — HTTP-backed, with config and typed failure++```python+import os+import httpx+from typing import Literal, Optional+from pydantic import Field+from atomic_agents import BaseIOSchema, BaseTool, BaseToolConfig+++class WeatherConfig(BaseToolConfig):+ api_key: str = Field(+ default_factory=lambda: os.environ.get("WEATHER_API_KEY", ""),+ description="API key for the weather service.",+ )+ base_url: str = Field(+ default="https://api.weather.example/v1",+ description="Base URL for the weather API.",+ )+ timeout: float = Field(default=15.0, ge=1.0, le=120.0, description="Request timeout (s).")+++class WeatherInput(BaseIOSchema):+ """A request for current weather conditions."""+ city: str = Field(..., description="City name, e.g. 'Brussels'.")+++class WeatherOutput(BaseIOSchema):+ """Current weather conditions, or a typed failure."""+ status: Literal["ok", "error"] = Field(..., description="Outcome code.")+ temperature_c: Optional[float] = Field(default=None, description="Temperature in Celsius.")+ summary: Optional[str] = Field(default=None, description="Human-readable summary.")+ error: Optional[str] = Field(default=None, description="Failure message when status='error'.")+++class WeatherTool(BaseTool[WeatherInput, WeatherOutput]):+ """Fetch current conditions for a city from the weather API."""++ def __init__(self, config: WeatherConfig | None = None):+ super().__init__(config or WeatherConfig())++ def run(self, params: WeatherInput) -> WeatherOutput:+ cfg: WeatherConfig = self.config+ if not cfg.api_key:+ return WeatherOutput(status="error", error="WEATHER_API_KEY not set")+ try:+ r = httpx.get(+ f"{cfg.base_url}/current",+ params={"city": params.city},+ headers={"Authorization": f"Bearer {cfg.api_key}"},+ timeout=cfg.timeout,+ )+ r.raise_for_status()+ except httpx.HTTPError as e:+ return WeatherOutput(status="error", error=str(e))+ data = r.json()+ return WeatherOutput(status="ok", temperature_c=data["temp_c"], summary=data["summary"])++ async def run_async(self, params: WeatherInput) -> WeatherOutput:+ cfg: WeatherConfig = self.config+ if not cfg.api_key:+ return WeatherOutput(status="error", error="WEATHER_API_KEY not set")+ async with httpx.AsyncClient(timeout=cfg.timeout) as client:+ try:+ r = await client.get(+ f"{cfg.base_url}/current",+ params={"city": params.city},+ headers={"Authorization": f"Bearer {cfg.api_key}"},+ )+ r.raise_for_status()+ except httpx.HTTPError as e:+ return WeatherOutput(status="error", error=str(e))+ data = r.json()+ return WeatherOutput(status="ok", temperature_c=data["temp_c"], summary=data["summary"])+```++### Hard rules++- Generic parameters carry the runtime type info. **Never** also assign `input_schema` / `output_schema` as class attributes — it shadows the framework-managed property.+- `run()` returns the **output schema instance**, not a dict.+- Secrets via env / `BaseToolConfig`, never hardcoded.+- HTTP tools always set a timeout. Tools run in the agent's request path.+- The async hook is `async def run_async`, not `arun` — the framework calls `run_async`.+- Convert routine failures (rate limits, 404s, validation rejects from the upstream API) into a typed failure output. Reserve `raise` for programmer error.++## Phase 4 — Wire it into an agent++Two integration shapes (see `../framework/references/tools.md` for more):++**Single-tool agent** — agent's output schema **is** the tool's input schema:++```python+agent = AtomicAgent[UserQuery, WeatherInput](config=config)+tool = WeatherTool()++call = agent.run(UserQuery(question="weather in Brussels?"))+result = tool.run(call)+```++**Router agent** — agent picks among tools via a discriminated union of tool-call schemas. Use this when the agent has 2–10 tools to choose from. For dozens, see the search+execute pattern in `../framework/references/orchestration.md`.++## Phase 5 — Verify++```bash+uv run python -c "from <project>.tools.<tool_name>_tool import <ToolName>Tool, <ToolName>Input; t = <ToolName>Tool(); print(t.run(<ToolName>Input(...)))"+```++If imports fail with the docstring error, add the docstring on the schema. If `self.input_schema` is `None`, the generic parameters are missing — write `class FooTool(BaseTool[FooInput, FooOutput]):`, not `class FooTool(BaseTool):`.++## Phase 6 — Hand off++Tell the user:++- Where the tool lives and what to import.+- How the agent should use it (single-tool or router shape).+- Optional next steps:+ - The agent that calls it → `create-atomic-agent` skill.+ - Multi-agent wiring around the tool → `../framework/references/orchestration.md`.+ - MCP interop or packaging the tool for distribution → `../framework/references/tools.md`.++## Anti-patterns++- `class FooTool(BaseTool):` with `input_schema = ...` class attributes — use generics: `BaseTool[FooInput, FooOutput]`.+- Returning a dict or primitive from `run()` instead of `OutputSchema(...)`.+- Raising on routine upstream failures — model them as typed output.+- No timeout on HTTP / DB calls.+- `MCPTransportType.STREAMABLE_HTTP` — the correct value is `HTTP_STREAM`.+- Implementing `async def arun(...)` — the framework calls `run_async`.++For deeper material — MCP interop, packaging a tool for `atomic download`, advanced router patterns — load `../framework/references/tools.md`.diff --git a/claude-plugin/atomic-agents/skills/framework/SKILL.md b/claude-plugin/atomic-agents/skills/framework/SKILL.mdindex 6d0fb40..1028326 100644--- a/claude-plugin/atomic-agents/skills/framework/SKILL.md+++ b/claude-plugin/atomic-agents/skills/framework/SKILL.md@@ -64,6 +64,19 @@ print(reply.chat_message)`AtomicAgent` and `BaseTool` use PEP 695 generics — the type parameters carry runtime information, so write them explicitly and keep them accurate. Full runnable version: `atomic-examples/quickstart/quickstart/1_0_basic_chatbot.py`.+## Targeted creation skills++For the four most common authoring tasks, dedicated atomic skills give a step-by-step workflow (clarify → write → verify → hand off) instead of just reference material. Prefer them when the user is actively building something specific.++| User intent | Atomic skill |+|---|---|+| "create a schema" / "design the input/output schema" | `atomic-agents:create-atomic-schema` |+| "create an agent" / "add another agent" / "wire up an `AtomicAgent`" | `atomic-agents:create-atomic-agent` |+| "add a tool" / "wrap an API as a tool" / "build a `BaseTool`" | `atomic-agents:create-atomic-tool` |+| "add a context provider" / "inject X into the prompt" / "wire up RAG" | `atomic-agents:create-atomic-context-provider` |++These skills auto-trigger on the matching phrasing. The reference files below are what they (and you) load for deeper material.+## Decision routingPick the reference file that matches the task. Each is loaded only when read.@@ -82,7 +95,7 @@ Pick the reference file that matches the task. Each is loaded only when read.| Decide the project layout or `pyproject.toml` | [references/project-structure.md](references/project-structure.md) || Write tests for agents and tools | [references/testing.md](references/testing.md) |-When a concept is unclear, start from the user's verb: *create a schema* → schemas, *hook up a weather API* → tools, *inject user name into prompt* → context providers, *route between agents* → orchestration.+When a concept is unclear, start from the user's verb: *create a schema* → `create-atomic-schema` skill, *hook up a weather API* → `create-atomic-tool` skill, *inject user name into prompt* → `create-atomic-context-provider` skill, *route between agents* → orchestration reference.## Working stylediff --git a/claude-plugin/atomic-agents/skills/new-app/SKILL.md b/claude-plugin/atomic-agents/skills/new-app/SKILL.mdindex aa3f800..9bdd7d8 100644--- a/claude-plugin/atomic-agents/skills/new-app/SKILL.md+++ b/claude-plugin/atomic-agents/skills/new-app/SKILL.md@@ -68,7 +68,9 @@ Use the template from `framework/references/project-structure.md`.Produce a runnable REPL. Load `.env`, instantiate the provider client per `framework/references/providers.md`, build an agent, wire a `ChatHistory` with a seed assistant message, loop on `console.input(...)`.-When a custom agent type was requested, build custom `InputSchema` / `OutputSchema` subclasses with field `description=` populated. Otherwise use `BasicChatInputSchema` / `BasicChatOutputSchema`.+For the agent itself, follow the workflow from the `atomic-agents:create-atomic-agent` skill — same canonical imports, same per-provider `mode` matrix, same `SystemPromptGenerator` shape.++When a custom agent type was requested, build custom `InputSchema` / `OutputSchema` subclasses with field `description=` populated, following the `atomic-agents:create-atomic-schema` skill. Otherwise use `BasicChatInputSchema` / `BasicChatOutputSchema`.Always use the canonical imports:@@ -115,9 +117,10 @@ After scaffolding, tell the user:1. How to set their key (`cp .env.example .env`).2. How to run (`uv run python -m <project_name>.main`).3. Next steps, picked from:- - Replace the starter schemas with domain-specific ones — see `framework/references/schemas.md`.- - Add a tool — see `framework/references/tools.md`.- - Add a context provider — see `framework/references/context-providers.md`.+ - Replace the starter schemas with domain-specific ones — use the `atomic-agents:create-atomic-schema` skill.+ - Add another agent — use the `atomic-agents:create-atomic-agent` skill.+ - Add a tool — use the `atomic-agents:create-atomic-tool` skill.+ - Add a context provider (time, user, RAG, session) — use the `atomic-agents:create-atomic-context-provider` skill.- Split into multiple agents — see `framework/references/orchestration.md`.4. A pointer to `framework` (auto-triggered) and `review` (auto-triggered before commit).