# AI Prompt - Implementation Workflow

## 1. Define the Use Case

| Question | Impact |
|----------|--------|
| Content type? | Model choice |
| Structured response? | OutputSchema |
| Multi-language? | Language variables |
| Budget limited? | ProviderInstance |
| Real-time? | Streaming |

## 2. Create the Prompt

```csharp
var promptId = await _promptService.CreatePromptAsync(new CreatePromptRequest
{
    Code = "ticket-analyzer",
    Name = "Ticket Analyzer",
    Blocks = new[] {
        new CreateBlockRequest {
            BlockType = PromptBlockType.System,
            Content = "Instructions...",
            IsRequired = true
        },
        new CreateBlockRequest {
            BlockType = PromptBlockType.User,
            Content = "Ticket: {{ticketTitle}}\nDescription: {{ticketDescription}}",
            IsRequired = true
        }
    }
});
```

## 3. Define OutputSchema (if structured response)

```csharp
var schemaId = await _schemaService.CreateAsync(new CreateSchemaRequest
{
    Code = "ticket-analysis-result",
    JsonSchema = @"{ ""type"": ""object"", ""required"": [""category"", ""priority""], ... }",
    DotNetType = "SmartStack.Application.AI.TicketAnalysisResult"
});
```

## 4. Execute the Prompt

```csharp
// Simple execution
var result = await _aiService.ExecutePromptAsync(promptId, new Dictionary<string, object>
{
    ["ticketTitle"] = ticket.Title,
    ["ticketDescription"] = ticket.Description
});

// With typed validation
var typedResult = await _aiService.ExecutePromptWithValidationAsync<TicketAnalysisResult>(
    promptId, variables);
if (typedResult.Success && typedResult.IsValid) { /* use typedResult.Data */ }
```

## AI Services

### IAiCompletionService
```csharp
Task<AiCompletionResult> CompleteAsync(AiCompletionRequest request, CancellationToken ct);
Task<AiCompletionResult> ExecutePromptAsync(Guid promptId, Dictionary<string, object>? variables, ...);
Task<AiValidatedCompletionResult<T>> ExecutePromptWithValidationAsync<T>(Guid promptId, ...);
Task<AiValidatedCompletionResult<T>> ExecutePromptByCodeWithValidationAsync<T>(string promptCode, ...);
```

### IPromptService
```csharp
Task<PromptDto> GetPromptByCodeAsync(string code, string? version = null);
Task<string> RenderPromptAsync(string code, Dictionary<string, object>? variables);
Task<Guid> CreatePromptAsync(CreatePromptRequest request);
Task ActivatePromptAsync(Guid promptId);
// Block management: AddBlockToPromptAsync, UpdateBlockAsync, ReorderBlocksAsync
```

## Frontend Integration

### API
```typescript
aiApi.getPrompts(status?, isTemplate?)
aiApi.executePrompt(promptId, variables)
aiApi.previewPrompt(promptId, variables)
aiApi.getProviders() / aiApi.getModels(providerId?)
aiApi.getSchemas() / aiApi.createSchema(data)
```

### Hook useAiCompletion
```typescript
const { execute, loading, error, result } = useAiCompletion<T>(promptCode);
const data = await execute(variables);
```

### Component AiAssistantButton
```tsx
<AiAssistantButton
  promptCode="ticket-analyzer"
  variables={{ ticketTitle, ticketDescription }}
  onResult={(result) => handleAnalysis(result)}
  label="Analyze with AI"
/>
```

## Advanced Patterns

### Streaming Response
```typescript
const reader = response.body?.getReader();
while (true) { const { done, value } = await reader.read(); if (done) break; /* append chunk */ }
```

### Fallback Provider
```csharp
foreach (var provider in providers.OrderBy(p => p.Priority)) {
    var result = await _aiService.ExecutePromptAsync(promptId, variables, providerId: provider.Id);
    if (result.Success) return result;
}
```
