---
name: ai-prompt
description: |
  Integrates AI capabilities into SmartStack features.
  Use this skill when:
  - User wants to integrate AI into a feature
  - User mentions "prompt", "GPT", "Claude", "IA", "AI"
  - Creating an assistant or chatbot
  - Automatic content generation
  - AI response validation with schema
  Types: Prompt, OutputSchema, Provider, Model
---

# Skill AI Prompt SmartStack

> **Architecture:** Prompt + Blocks -> Provider + Model -> Completion -> Schema Validation
> Multi-provider: OpenAI, Anthropic (Claude), Azure OpenAI, Google Gemini

**Reference:** [_shared.md](../_shared.md) for common patterns

## When This Skill Activates

| Trigger | Example |
|---------|---------|
| Explicit request | "Integrate GPT to generate descriptions" |
| Chatbot/Assistant | "Create an assistant for support" |
| Content generation | "Auto-generate responses" |
| Text analysis | "Analyze the sentiment of comments" |
| Keywords | "prompt", "GPT", "Claude", "IA", "completion", "LLM" |

## AI Flow

```
Feature -> IAiCompletionService.ExecutePromptAsync()
    |
Prompt + Blocks -> Provider Instance -> External API (OpenAI/Claude/Azure/Gemini)
    |
AI Response -> OutputSchema Validation -> Typed Result<T>
```

## Main Entities

### AiProvider & AiModel
- **Providers:** OpenAI, Anthropic, Azure OpenAI, Google
- **Models:** gpt-4o, claude-opus-4-6/sonnet-4-6/haiku-4-5, gemini-pro
- Properties: Code, ContextWindow, MaxOutputTokens, InputCost, OutputCost, SupportsVision, SupportsStreaming

### AiProviderInstance
Configured instance: Code, Name, SystemContext, DefaultModel, MonthlyBudgetLimit, EncryptedApiKey

### Prompt & PromptBlock
```csharp
// Prompt: Code, Name, Version, Status, IsTemplate, OutputSchemaId, Blocks
// PromptBlockType: System, User, Assistant, Tool, Context, Examples
// Block: Label, Content, DisplayOrder, IsRequired, Condition
```

### OutputSchema
JSON Schema for validation: Code, Name, JsonSchema, DotNetType

### AiAgent (R17 — v3.46+)
Multi-step agent with reasoning modes. See [references/ai-agent-modes.md](references/ai-agent-modes.md).

- **AiAgentMode** : `Sequential` (0), `ReAct` (1), `PlanAndExecute` (2), `SelfCorrection` (3)
- **AiAgentStepRole** : `Worker` (0), `Planner` (1), `Reasoner` (2), `Critic` (3), `Synthesizer` (4)
- **MaxIterations** (default 5, range 1-20) — protects against infinite loops
- **QualityThreshold** (default 0.8) — used by `SelfCorrection` mode
- **AiSkill.CacheTtlSeconds** + **AiSkillBlock.IsCacheable** — caching for idempotent outputs

Default to `Sequential` ; switch to `ReAct`/`PlanAndExecute`/`SelfCorrection` only when needed (cost/latency impact).

### AiTool — function calling (R2 — v3.46+)

Server-side function the model can decide to invoke during a completion. Tools turn skills from one-shot prompts into agentic workflows that can read live data, call external APIs, and condition output on the result.

```csharp
class AiTool : BaseEntity, IAuditableEntity
{
    public string Name { get; }                  // Snake_case, presented to model: "search_database"
    public string DisplayName { get; }           // Admin UI label
    public string Description { get; }           // Drives model decision — short, action-oriented
    public string ParametersSchemaJson { get; }  // JSON Schema of tool arguments
    public string HandlerKey { get; }            // Stable key → IToolHandler dispatcher
    public Guid ModuleId { get; }                // Module owns the tool (permissions + admin grouping)
    public bool IsActive { get; }
}
```

- **Many-to-many** with `AiSkill` via `AiSkillTool` (kept as own entity for future per-attachment overrides : required flag, parameter aliasing, max-call budget).
- **HandlerKey** decouples definition from C# class name (handlers can be renamed without breaking the catalog).
- When `IsActive = false`, the orchestrator skips the tool even if a skill still references it.

**DO / DON'T:**
- DO author tool descriptions for the model — short, action-oriented, with preconditions
- DO snake_case the `Name` (LLM convention)
- DON'T expose long-running or heavy tools via function calling — prefer Workflow steps
- DON'T duplicate tool logic across skills — attach the same `AiTool` via `AiSkillTool`

### AiAgentExecution — runtime tracking

Each execution of an `AiAgent` is recorded via `AiAgentExecution` with:
- `Status` : `Running` / `Completed` / `Failed` / `PartiallyCompleted` / `Cancelled`
- `ExecutedSteps` / `TotalSteps`
- `InputStateJson` / `FinalStateJson` (audit trail)
- **Usage tracking** : `TotalInputTokens`, `TotalOutputTokens`, `TotalCost` (decimal), `TotalExecutionTimeMs`
- `_stepExecutions` : per-step `AiAgentStepExecution` (with own status, tokens, cost)

Service methods : `IncrementExecutedSteps()`, `MarkCompleted(json)`, `MarkFailed(msg)`, `MarkPartiallyCompleted(json, msg)`, `MarkCancelled(msg)`, `AccumulateUsage(in, out, cost, ms)`, `AddStepExecution(step)`.

**Use** : surface in admin UI (run history, cost dashboard, debug trace). Each agent run produces one `AiAgentExecution` + N `AiAgentStepExecution`.

### AI Evaluation Framework (R10)

For benchmarking skills against expected outputs, see [references/eval-framework.md](references/eval-framework.md). Pattern: `AiEvalDataset` (test cases) + `AiEvaluation` (one run) + `AiEvalResult` (per-item outcome). Provider/model agnostic — same dataset can compare 2 versions of the same skill code.

## Implementation

Start with [steps/step-00-init.md](steps/step-00-init.md) to gather requirements, then proceed to [steps/step-01-implementation.md](steps/step-01-implementation.md) for:
- Workflow steps (define use case, create prompt, define schema, execute)
- AI service interfaces (IAiCompletionService, IPromptService)
- Frontend integration (API, hooks, components)
- Advanced patterns (streaming, fallback provider)

## Checklist

```
- Prompt created (unique Code, Blocks, Variables, Version)
- OutputSchema if structured response
- Service with IAiCompletionService injected
- Error handling + Logging (tokens, time)
- Frontend: Hook/component, Loading, Error handling
- ProviderInstance with budget limit
- Tests: execution, variables, schema validation
```

## Absolute Rules

| DO | DON'T |
|----|-------|
| IAiCompletionService for executions | Direct API calls |
| OutputSchema for structured responses | Unvalidated responses |
| Error handling (API down, quota) | Ignore token limits |
| Log executions (tokens, duration) | Hardcode API keys |
| Variables for dynamic content | Expose system prompts to frontend |

## Key Files

| File | Role |
|------|------|
| `Domain/AI/Prompts/Prompt.cs` | Prompt entity |
| `Domain/AI/Schemas/OutputSchema.cs` | Schema validation |
| `Domain/AI/AiProviderInstance.cs` | Configured instance |
| `Domain/AI/Agents/AiAgent.cs` | Multi-step agent (R17 — v3.46+) |
| `Domain/AI/Agents/AiAgentStep.cs` | Agent step with `Role` (Worker/Planner/Reasoner/Critic/Synthesizer) |
| `Domain/AI/Agents/AiAgentExecution.cs` | Run tracking (status, tokens, cost, step executions) |
| `Domain/AI/Skills/AiSkill.cs` | Reusable skill (`CacheTtlSeconds` for cache hint) |
| `Domain/AI/Tools/AiTool.cs` | Function-calling tool (R2 — v3.46+) |
| `Domain/AI/Tools/AiSkillTool.cs` | Many-to-many AiSkill ↔ AiTool |
| `Domain/AI/Evaluations/AiEvalDataset.cs` | Eval dataset (R10 — v3.46+) |
| `Domain/AI/Evaluations/AiEvaluation.cs` | Eval run with rollup stats |
| `Application/Common/Interfaces/IAiCompletionService.cs` | Service interface |
| `Application/Common/Interfaces/IToolHandler.cs` | Tool handler interface (resolved via HandlerKey) |
| `Infrastructure/Services/AI/AiCompletionService.cs` | Implementation |
| `web/src/services/api/aiApi.ts` | Frontend API |

<success_criteria>
- Prompt entity created with OutputSchema validation
- IAiCompletionService integration wired correctly
- Error handling for API failures and quota limits implemented
- Token usage logged per execution
</success_criteria>
