Pular para conteúdo

Fluxo: Playground Pipeline

Visão Geral

O Playground permite que administradores testem o agente diretamente pelo portal antes de colocá-lo em produção. O chat do playground simula uma conversa real, montando o system prompt completo (com base de conhecimento, etapas, anexos e regras) da mesma forma que a conversa via WhatsApp.

Arquitetura

┌─────────────────────────────────────────────────────────────────────┐
│  POST /api/agents/{agentId}/playground/chat                         │
│  ► PlaygroundChatHandler (MediatR)                                  │
│  ► Pipeline<PlaygroundPipelineContext>                               │
├─────────────────────────────────────────────────────────────────────┤
│                                                                     │
│  ┌──────────────────┐                                               │
│  │ 1. LoadPlayground│ Carrega agente com steps, knowledge,          │
│  │    AgentStep     │ FAQs e attachments (split query)              │
│  │                  │ → context.Agent                                │
│  └────────┬─────────┘                                               │
│           ▼                                                         │
│  ┌──────────────────┐                                               │
│  │ 2. CheckPlaygr.  │ Verifica créditos da subscription             │
│  │    CreditsStep   │ → context.HasSubscription                     │
│  └────────┬─────────┘                                               │
│           ▼                                                         │
│  ┌──────────────────┐                                               │
│  │ 3. PreparePlaygr.│ Converte PlaygroundMessageDto[]               │
│  │    MessagesStep  │ para ChatMessage[] (texto + imagem)           │
│  │                  │ → context.ChatMessages                         │
│  └────────┬─────────┘                                               │
│           ▼                                                         │
│  ┌──────────────────┐                                               │
│  │ 4. BuildPlaygr.  │ Monta system prompt completo:                 │
│  │    PromptStep    │ base + knowledge + steps + attachments        │
│  │                  │ com prompt caching (SystemPromptBlocks)        │
│  │                  │ → context.SystemBlocks                         │
│  └────────┬─────────┘                                               │
│           ▼                                                         │
│  ┌──────────────────┐                                               │
│  │ 5. ClassifyPlaygr│ Classifica intent via Haiku                   │
│  │    IntentStep     │ (jailbreak → bloqueia, FAQ → Haiku)          │
│  │                  │ → context.IntentClassification                 │
│  └────────┬─────────┘                                               │
│           ▼                                                         │
│  ┌──────────────────┐                                               │
│  │ 6. GeneratePlaygr│ Chama Claude API via ILlmClient               │
│  │    ResponseStep  │ → context.LlmResponse                         │
│  └────────┬─────────┘                                               │
│           ▼                                                         │
│  ┌──────────────────┐                                               │
│  │ 7. ValidatePlaygr│ Valida resposta via guardrails rule-based     │
│  │    OutputStep     │ (PII masking, promessas)                     │
│  │                  │ → context.LlmResponse (sanitized)             │
│  └────────┬─────────┘                                               │
│           ▼                                                         │
│  ┌──────────────────┐                                               │
│  │ 8. ConsumePlaygr.│ Decrementa crédito da subscription            │
│  │    CreditStep    │ + notifica frontend via SignalR                │
│  └────────┬─────────┘                                               │
│           ▼                                                         │
│  ┌──────────────────┐                                               │
│  │ 9. TrackPlaygr.  │ Registra uso de tokens (fire-and-forget)      │
│  │    UsageStep     │ via ILlmUsageTracker                          │
│  └────────┬─────────┘                                               │
│           ▼                                                         │
│  ┌──────────────────┐                                               │
│  │ 10. ParsePlaygr. │ Extrai texto da resposta do LLM               │
│  │    ResponseStep  │ → context.Result (PlaygroundChatResponse)     │
│  └──────────────────┘                                               │
│                                                                     │
└─────────────────────────────────────────────────────────────────────┘

Contexto do Pipeline

PlaygroundPipelineContext
├── Input (init)
   ├── Request: PlaygroundChatRequest
   └── TenantId: Guid
├── Loaded
   ├── Agent: Agent?                  LoadPlaygroundAgentStep
   └── HasSubscription: bool          CheckPlaygroundCreditsStep
├── Prepared
   ├── ChatMessages: List<ChatMessage>           PreparePlaygroundMessagesStep
   ├── SystemBlocks: List<SystemPromptBlock>     BuildPlaygroundPromptStep
   └── ActiveAttachments: List<AgentAttachment>  BuildPlaygroundPromptStep
├── Intent Classification
   ├── IntentClassification: IntentClassification?   ClassifyPlaygroundIntentStep
   ├── ClassifiedModelOverride: string?              ClassifyPlaygroundIntentStep
   ├── SkipLlmCall: bool                            ClassifyPlaygroundIntentStep
   └── CannedResponse: string?                      ClassifyPlaygroundIntentStep
├── Generated
   └── LlmResponse: LlmResponse?     GeneratePlaygroundResponseStep
└── Output
    └── Result: Result<PlaygroundChatResponse>?   ParsePlaygroundResponseStep

Diferença vs AI Assistant

Aspecto AI Assistant Playground
Propósito Ajuda a criar o conteúdo do agente Testa o agente como se fosse um cliente
System Prompt Template especializado por seção System prompt completo do agente (produção)
Contexto Conteúdo sendo editado + histórico do chat Histórico de mensagens do playground
Resposta JSON estruturado (suggested_content + message) Texto livre (resposta do agente)
Suporte a imagens Não Sim (Claude Vision)
Knowledge/Steps Passados como contexto textual Montados no system prompt

Montagem do System Prompt (BuildPlaygroundPromptStep)

O step BuildPlaygroundPromptStep reproduz a mesma lógica do AiResponseService usado no WhatsApp:

  1. Prompt baseAgent.OptimizedSystemPrompt (otimizado) ou Agent.Prompt (original)
  2. Base de conhecimento — blocos ativos concatenados
  3. Etapas — etapas ativas ordenadas com instruções
  4. Anexos — attachments ativos com conteúdo textual
  5. Prompt caching — blocos marcados com CacheControl para otimizar tokens

Arquivos Relevantes

Arquivo Descrição
Api/Features/Agents/Playground/PlaygroundHandler.cs Handler MediatR (chat)
Api/Features/Agents/Playground/Pipeline/ Steps do pipeline (10 steps)
Shared/Features/Agents/Playground/ Requests, Responses
Infrastructure/Services/Llm/AttachmentPromptHelper.cs Helper para montar prompt de anexos