Format for contracts/ai.md, the single source of truth for AI/LLM integration between the backend, the AI engineer, and the frontend. The architect writes it. Everyone else reads it.
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 Contract?
Add the live security badge to your README. It updates with every re-scan.
[](https://www.skillsdirectory.com/skills/sayeed1999-ai-contract)
---
name: ai-contract
description: Format for contracts/ai.md, the single source of truth for AI/LLM integration between the backend, the AI engineer, and the frontend. The architect writes it. Everyone else reads it.
---
# ai-contract
Output: `contracts/ai.md`. Used by the architect.
## Steps
### 1. Check AI is needed
- If no approved requirement needs AI or LLM features, do not write the file.
### 2. Map each requirement to one tool
- 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.
- Record every AI-related R-ID in the Capability map.
- `tool-call`: the LLM picks this tool and its parameters. The backend runs the prewritten query or service function.
- `rag`: one tool that answers from documents, articles, manuals, or FAQs. The backend retrieves chunks and injects `{context}`.
- `text-only`: one tool for drafting, summarizing, or classifying provided text. No database query.
- Query generation is not the default.
### 3. Write the header, memory, and backend interface
- Use the Header format below.
- Set `Runtime` from `skills/stack-defaults`, AI runtime. Name the R-IDs behind anything other than `direct`.
- Define the conversation memory mode (stateless or sliding window).
- Define the exact backend integration callable signature so backend-engineer can wire the endpoint without editing the AI folder.
### 4. Write the tool definitions
- One block per tool, in the Tool format below.
- Each AI task is one tool.
- Set `Execution` on every tool to state whether `ai-engineer` writes the prewritten parameterized query in `ai/` (via `db/session`) or calls a named `db/` query written by `backend-engineer`.
- The backend runs that tool. The model does not receive database rows.
### 5. Write the retrieval rules (if applicable)
- Only when at least one R-ID uses `rag`.
- Use the Retrieval format below.
### 6. Write the workflow graph (runtime `langgraph` or `langgraph+langchain`)
- Use the Workflow graph format below. One block per workflow.
- Every node, edge condition, and interrupt names the R-ID that needs it.
- `contracts/api.md` gets the matching endpoints: start a run, send a human decision, read a run's state.
### 7. Query generation (optional later path)
- Do not write this section unless the user explicitly asks for generated queries.
- Query generation is not the default.
- When the user asks, use the Query generation format below.
### 8. Check it
- `Runtime` is set. A workflow graph exists if, and only if, the runtime uses `langgraph`.
- Every AI-related R-ID is listed in the Capability map.
- Each AI task is one tool.
- Backend integration interface defines the exact file, function name, and signature.
- Memory mode and max turns are defined.
- If RAG is used, document source, chunking, embedding, storage, and grounding are written.
- Every tool lists its R-IDs and `Execution` location.
- Every parameter has a type, required or optional, and rules.
- Every tool return has the exact JSON shape.
- The system prompt template is written. Use `{context}` for RAG.
- Use `{schema}` only when the query generation section exists.
- Error cases are listed.
- No query generation section unless the user explicitly asked for generated queries.
## Format: header
```
# AI Contract
- Provider: <from architecture, e.g. OpenAI, Anthropic, Google>
- Model: <from architecture, e.g. gpt-4o, claude-sonnet-4-20250514>
- Runtime: <direct | langgraph | langgraph+langchain> - <R-IDs and reason, or "default">
- Backend module: <ai folder path, e.g. api/ai/>
- MCP: <none | client: server name, URL env var, tools used | server: tools exposed, R-IDs>
- Chat endpoint: <the API endpoint that receives user messages, e.g. POST /v1/chat>
- Auth: <same as API contract auth>
## Capability map
- R-02: tool-call (known stock lookups)
- R-03: rag (answering FAQ and policies from documents)
## Memory
- Mode: <stateless | sliding_window | full_history>
- Max turns: <e.g. 6 turns, or n/a if stateless>
- Source: <client sends history array | server database session>
## Backend integration interface
- Entrypoint: <file path, e.g. api/ai/service.py or api/ai/service.go>
- Callable: <exact function name and signature, e.g. process_chat(message: str, history: list[dict]) -> dict>
## System prompt
<The exact system prompt template. Use {context} for RAG. Use {schema} only when the user asked for generated queries. The model chooses a tool. The backend runs it. The model does not receive database rows.>
## Error format (AI errors)
- Provider timeout: return 503 AI_PROVIDER_TIMEOUT
- Provider error: return 502 AI_PROVIDER_ERROR
- Unsafe query: return 422 UNSAFE_QUERY
- Unknown tool: return 400 UNKNOWN_TOOL
```
## Format: tool
```
### Tool: get_low_stock_products
- R-IDs: R-05
- Execution: prewritten parameterized SELECT in `ai/tools.py` using the session from `database.py`
- Description: Returns products with stock below the given threshold
- Parameters:
- threshold: integer, required, min 0
- Returns:
{ "products": [{ "id": "string", "name": "string", "stock": 0 }] }
- Errors:
- VALIDATION_ERROR: threshold is negative
```
## Format: retrieval (RAG)
```
## Retrieval (RAG)
- R-IDs: R-03
- Document source: <e.g. docs/faq/, knowledge_articles table, or uploaded files>
- Chunking: <e.g. 500 characters, 50 character overlap>
- Embedding: <provider and model, e.g. text-embedding-3-small, or none if FTS>
- Storage: <pgvector in PostgreSQL | sqlite-vec | FTS5 in SQLite>
- Top K: <e.g. 3 chunks>
- Grounding: <exact rule, e.g. answer strictly from retrieved context; state "I do not have enough information" if missing; cite document title>
```
## Format: workflow graph
Only for runtime `langgraph` or `langgraph+langchain`.
```
## Workflow: refund_request
- R-IDs: R-07, R-08
- Entrypoint: <file and callable, e.g. api/ai/graphs/refund.py start_refund(thread_id: str, message: str) -> dict>
- State:
- order_id: string, optional
- reason: string, optional
- decision: approve | reject, optional
- status: collecting | reviewing | done
- Nodes:
- collect: asks for missing order_id or reason (R-07)
- check_policy: calls tool get_order (R-07)
- human_review: interrupt; staff approve or reject (R-08)
- finish: writes the refund and replies (R-08)
- Edges:
- start -> collect
- collect -> collect when order_id or reason is missing, else -> check_policy
- check_policy -> human_review
- human_review -> finish
- Interrupts: human_review waits for POST /v1/refunds/{thread_id}/decision
- Checkpointer: <postgres | sqlite>, thread_id = <what one thread is, e.g. one refund request>
- Recursion limit: 25
```
## Format: query generation
Optional later path. Do not write this section unless the user explicitly asks for generated queries.
```
## Query generation
- Allowed verbs: SELECT only
- Schema source: <database introspection | checked-in file>
- Tables exposed: <list, or "all" with exclusions>
- Tables excluded: <list of sensitive tables, e.g. users, sessions, tokens>
- Row limit: <default 100>
- Validation: every table and column name checked against schema before execution
- Parameters: all dynamic values parameterized, never interpolated
```
## Changing the AI contract
- Only the architect edits it.
- Under a changed tool add `Changed: <date> <reason>`.
- If the tool is built or being built, write a handoff to ai-engineer.
## MUST
- 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.
- Map every AI R-ID in the Capability map.
- Specify Memory mode and max turns in the header.
- List every tool the LLM can call and its `Execution` location.
- Specify Document source, chunking, embedding, storage, and grounding when RAG is used.
- Write the system prompt template.
- Specify the Backend integration interface with file and callable signature.
- When the query generation section exists, specify which tables are excluded.
## NEVER
- Add a tool without an approved requirement.
- Send database rows to the model.
- Write the query generation section unless the user explicitly asks for generated queries.
- Add an external vector database when PostgreSQL (pgvector) or SQLite already exists.
- Choose `langgraph` for a Q&A bot with no workflow signal.
- Allow write queries in the query generation section.
- Expose sensitive tables (users, sessions, tokens) to query generation.