Step-by-step rules for AI/LLM integration tasks. The LLM chooses a tool. The backend runs it. Query generation runs only when the AI contract has a query-generation section. Used by ai-engineer only.
Installs into .claude/skills of the current project.
Sponsors
SSkills DirectorySkills Directory
Know which skills are safe — weekly.
SSkills DirectorySkills Directory
Is that skill safe to install?
Are you the author of Ai Impl?
Add the live security badge to your README. It updates with every re-scan.
[](https://www.skillsdirectory.com/skills/sayeed1999-ai-impl)
---
name: ai-impl
description: Step-by-step rules for AI/LLM integration tasks. The LLM chooses a tool. The backend runs it. Query generation runs only when the AI contract has a query-generation section. Used by ai-engineer only.
---
# ai-impl
Examples use the default stack (FastAPI). If `docs/architecture.md` names another stack, use its folders and commands and keep the same rules.
## Steps
### 1. Read
- Read `docs/tasks/T-NN.md`. It names everything else you read.
- Read `docs/architecture.md`: AI provider, model, layout, commands, error format, logging.
- Read `contracts/ai.md`: tool definitions, parameter schemas, response shapes, system prompt rules.
- Read `contracts/api.md` for endpoints that call your AI module.
- Read the tables your tools use in `docs/schema.md`.
### 2. Plan the files
- Task title has `Foundation`: build the provider client, config, tool registry, and the retriever when RAG is used. Runtime `langgraph`: also the checkpointer. Add a schema loader only when `contracts/ai.md` has a Query generation section.
- Every task: one file per concern inside the `ai/` folder.
- MCP in the task: build `mcp-client/` or `mcp-server/` per `skills/stack-defaults`, MCP. They import nothing from `ai/`, `internal/`, or the service.
### 3. Build in this order
- Provider client: one place for the API key, model name, embeddings client (if RAG), timeout, and retry logic.
- Retriever (when RAG is used): document loader, chunking, embeddings generator, and vector search over the project database table.
- Tool definitions: one function per tool listed in `contracts/ai.md`. The LLM chooses the tool. Each function returns structured data, not free text.
- Prompt templates: system prompt and tool descriptions exactly as `contracts/ai.md` specifies. Inject `{context}` for RAG. Inject `{schema}` only when `contracts/ai.md` has a Query generation section.
- Schema loader (only when `contracts/ai.md` has a Query generation section): reads the database schema at startup or on demand. Caches it.
- Query generator (only when `contracts/ai.md` has a Query generation section): takes the LLM output, validates it against the loaded schema, and returns a parameterized `SELECT` query.
- Runtime `langgraph`: one graph per workflow in `ai/graphs/<workflow>.py`, built in the order of the Workflow graph section (LangGraph rules below).
- Orchestrator function: export the exact callable specified under Backend integration interface in `contracts/ai.md`. Manages conversation memory, retrieves `{context}` (if RAG), calls the LLM with tools, runs the chosen tool, and returns the final response. The model does not receive database rows.
### 4. Test
- Target `prototype`: skip this step (`AGENTS.md`, Target).
- Per tool: one test with a mocked LLM response that returns a tool call, and one test that the tool executes correctly.
- RAG retriever: one test that query returns relevant chunks, and one test that an empty or missing match returns empty context.
- Query generator, only when `contracts/ai.md` has a Query generation section: one test with a valid query, one with a disallowed verb (`INSERT`, `DELETE`), and one with a table not in the schema.
- Provider errors: one test that a timeout or provider error returns the contract error format.
- Runtime `langgraph`: one test per edge condition, and one test that an interrupted run resumes from its checkpoint.
- One test per Acceptance line of the spec that the tests above do not cover.
### 5. Check
- Run the lint and test commands from `docs/architecture.md`.
- Start the server and confirm the AI endpoint responds.
- Tick the Done checklist.
## Tool definition rules
- Each AI task is one tool. The LLM chooses which tool to call.
- The backend runs that tool. The model does not receive database rows.
- Each tool has a name, description, and a JSON Schema for its parameters, matching `contracts/ai.md`.
- Tool functions receive validated parameters and return structured data.
- Tool functions do not call the LLM. They call the database or a service.
- Tool functions use the ORM or parameterized queries. Never string-built SQL.
- Generate a query only when `contracts/ai.md` has a Query generation section.
## RAG rules
- Document chunk size and overlap match `contracts/ai.md`.
- Embeddings are generated with the model and provider named in `contracts/ai.md`.
- Store vector embeddings in the configured database (e.g. pgvector column or sqlite-vec table).
- Pass user query to retriever, fetch top_k chunks, and inject into `{context}` in the prompt.
- When no chunks match or context is empty, pass empty `{context}` so system prompt grounding triggers refusal.
## LangGraph rules
- Apply these only when `contracts/ai.md` sets runtime `langgraph` or `langgraph+langchain`.
- The state schema is a `TypedDict` with exactly the fields in the Workflow graph section.
- Node and edge names match the contract. Conditional edges are plain functions over the state.
- Nodes call tools and the provider client. Tools stay plain functions, as in Tool definition rules.
- Human steps use `interrupt()`. Resume with the decision the contract's endpoint receives.
- The checkpointer comes from config and uses the project database. Call its `setup()` once at startup.
- Every run passes `thread_id` and the contract's recursion limit.
- Runtime `langgraph`: no LangChain packages. Runtime `langgraph+langchain`: only the LangChain components the contract names.
- Tests use a fake model and an in-memory checkpointer (`InMemorySaver`).
## Query generation rules
- Apply these rules only when `contracts/ai.md` has a Query generation section.
- Only `SELECT` statements. Reject anything else before execution.
- Parse the LLM output and validate every table and column name against the loaded schema.
- Parameterize all dynamic values. Never interpolate user input.
- Set a row limit (default 100) on every generated query.
- Log the validated query at `info` level (without parameter values that may contain PII).
## Schema introspection rules
- Apply these rules only when `contracts/ai.md` has a Query generation section.
- Load table names, column names, and column types from the database or from a checked-in schema file.
- Never expose the schema to the frontend or to chat responses.
- Cache the schema in memory. Reload on explicit request or on server restart.
## When something is wrong
- The backend endpoint shape does not match `contracts/api.md`: send a handoff to backend-engineer.
- The AI contract or the task spec is wrong or incomplete: send a handoff to architect.
- A table or column your tool needs is missing or wrong in `docs/schema.md`: send a handoff to database-engineer.
- No provider key in `.env` and the task needs a live check: raise an `env` blocker.
- If it stops you, set the task `blocked` (`skills/flow`, Blockers).
## Done checklist
- Every Acceptance line of the spec passes.
- Tools match the AI contract.
- RAG chunking, retriever, and context grounding match the contract.
- Query generation is read-only and parameterized when the contract has a Query generation section.
- Schema validation rejects unknown tables and columns when the contract has a Query generation section.
- Provider errors return the contract error format.
- Config and logger are used through the config and logger files of the layout.
- `.env.example` is updated with AI provider variables.
- Lint and tests pass (`prototype`: lint only). The server starts.
- Task is `built`.
## MUST
- Export the exact entrypoint callable specified under Backend integration interface in `contracts/ai.md`.
- Ground RAG answers strictly in retrieved context.
- Keep the orchestrator function thin: parse, call LLM, dispatch tool calls, format response.
- All provider config comes from env through the config file in `docs/architecture.md` section 3.
- Mock embeddings and the LLM in automated tests. Never call the real provider in automated tests.
## NEVER
- Change the contract or invent tools.
- Call external vector SaaS services outside the project database.
- Add LangGraph or LangChain when the contract says runtime `direct`.
- Execute write queries from LLM output.
- Return raw LLM output without validation.
- Log prompts, completions, or user messages that may contain PII.
- Import feature folders. Use only the shared config, logger, and database files, `external-services/` interfaces, and `mcp-client/`.
- Read env vars outside the config file.