# Multi-Agent System - Especificação

## 1. Visão Geral

Sistema de agentes de IA cooperativos usando Microsoft Semantic Kernel para resolver tarefas complexas através de decomposição e especialização.

### 1.1 Objetivos

- Criar sistema escalável de agentes cooperativos
- Implementar orquestração inteligente de tarefas
- Fornecer extensibilidade para novos agentes e plugins
- Manter custos controlados com uso eficiente de tokens

### 1.2 Use Cases

| Use Case | Agentes Envolvidos |
|----------|-------------------|
| Pesquisa de mercado | Orchestrator → Research → Analysis → Writing |
| Análise de documentos | Orchestrator → Research → Analysis |
| Geração de relatórios | Orchestrator → Research → Writing |
| Q&A com base de conhecimento | Orchestrator → Research |

## 2. Arquitetura

### 2.1 Componentes Principais

```
┌─────────────────────────────────────────────────────────────────┐
│                        API Layer                                 │
│  ┌─────────────────┐  ┌─────────────────┐                       │
│  │  ChatEndpoints  │  │  AgentEndpoints │                       │
│  └─────────────────┘  └─────────────────┘                       │
└─────────────────────────────────────────────────────────────────┘
                              │
                              ▼
┌─────────────────────────────────────────────────────────────────┐
│                    Orchestration Layer                           │
│  ┌─────────────────┐  ┌─────────────────┐  ┌─────────────────┐ │
│  │ TaskDecomposer  │  │  AgentRouter    │  │ ResultAggregator│ │
│  └─────────────────┘  └─────────────────┘  └─────────────────┘ │
└─────────────────────────────────────────────────────────────────┘
                              │
                              ▼
┌─────────────────────────────────────────────────────────────────┐
│                      Agent Layer                                 │
│  ┌──────────────┐  ┌──────────────┐  ┌──────────────────────┐  │
│  │ Research     │  │ Analysis     │  │ Writing              │  │
│  │ Agent        │  │ Agent        │  │ Agent                │  │
│  └──────────────┘  └──────────────┘  └──────────────────────┘  │
└─────────────────────────────────────────────────────────────────┘
                              │
                              ▼
┌─────────────────────────────────────────────────────────────────┐
│                      Plugin Layer                                │
│  ┌─────────────┐  ┌─────────────┐  ┌─────────────┐             │
│  │ WebSearch   │  │ Document    │  │ DataAnalysis│             │
│  │ Plugin      │  │ Plugin      │  │ Plugin      │             │
│  └─────────────┘  └─────────────┘  └─────────────┘             │
└─────────────────────────────────────────────────────────────────┘
                              │
                              ▼
┌─────────────────────────────────────────────────────────────────┐
│                    Infrastructure Layer                          │
│  ┌─────────────────┐  ┌─────────────────┐  ┌─────────────────┐ │
│  │  Azure OpenAI   │  │  Vector Store   │  │  Memory Store   │ │
│  └─────────────────┘  └─────────────────┘  └─────────────────┘ │
└─────────────────────────────────────────────────────────────────┘
```

### 2.2 Fluxo de Dados

```
User Request
    │
    ▼
┌─────────────────────────────────────────┐
│           Task Decomposition            │
│  "Compare cloud providers" →            │
│  [Research AWS, Research Azure,         │
│   Research GCP, Compare, Write Report]  │
└─────────────────────────────────────────┘
    │
    ▼
┌─────────────────────────────────────────┐
│           Agent Execution               │
│  Research Agent → findings[]            │
│  Analysis Agent → insights              │
│  Writing Agent → report                 │
└─────────────────────────────────────────┘
    │
    ▼
┌─────────────────────────────────────────┐
│         Result Aggregation              │
│  Combine outputs, format, validate      │
└─────────────────────────────────────────┘
    │
    ▼
Final Response
```

## 3. Requisitos Funcionais

### 3.1 API

| ID | Requisito |
|----|-----------|
| API-001 | Endpoint de chat para interação com usuário |
| API-002 | Endpoint para consultar status de processamento |
| API-003 | Endpoint para listar agentes disponíveis |
| API-004 | Streaming de respostas (SSE) |
| API-005 | Autenticação via API Key |

### 3.2 Orchestrator

| ID | Requisito |
|----|-----------|
| ORCH-001 | Análise de intenção do usuário |
| ORCH-002 | Decomposição de tarefas complexas |
| ORCH-003 | Roteamento para agentes especialistas |
| ORCH-004 | Agregação de resultados |
| ORCH-005 | Retry automático em falhas |
| ORCH-006 | Timeout por subtarefa |

### 3.3 Agentes

| ID | Requisito |
|----|-----------|
| AGT-001 | Research Agent com acesso a web search |
| AGT-002 | Research Agent com RAG (vector search) |
| AGT-003 | Analysis Agent para comparações |
| AGT-004 | Analysis Agent para insights |
| AGT-005 | Writing Agent para relatórios |
| AGT-006 | Writing Agent para sumários |

### 3.4 Plugins

| ID | Requisito |
|----|-----------|
| PLG-001 | WebSearch via Bing API |
| PLG-002 | Document retrieval via vector store |
| PLG-003 | Calculator para análises numéricas |
| PLG-004 | Date/Time utilities |

### 3.5 Memória

| ID | Requisito |
|----|-----------|
| MEM-001 | Conversation memory por sessão |
| MEM-002 | Semantic memory para contexto relevante |
| MEM-003 | Persistência opcional em Cosmos DB |

## 4. Requisitos Não-Funcionais

### 4.1 Performance

| ID | Requisito |
|----|-----------|
| PERF-001 | Response streaming para UX fluida |
| PERF-002 | Timeout máximo de 60s por request |
| PERF-003 | Execução paralela de subtarefas independentes |

### 4.2 Custo

| ID | Requisito |
|----|-----------|
| COST-001 | Limite de tokens por request configurável |
| COST-002 | Uso de modelos menores para subtarefas simples |
| COST-003 | Cache de resultados de pesquisa |
| COST-004 | Tracking de uso de tokens |

### 4.3 Segurança

| ID | Requisito |
|----|-----------|
| SEC-001 | API Key authentication |
| SEC-002 | Rate limiting por API key |
| SEC-003 | Input sanitization |
| SEC-004 | Output filtering (PII, harmful content) |

## 5. Agentes em Detalhe

### 5.1 Orchestrator Agent

**System Prompt**:
```
You are an orchestrator agent responsible for coordinating other specialized agents.

When you receive a user request:
1. Analyze the intent and complexity
2. Decompose into subtasks if needed
3. Delegate to appropriate specialist agents
4. Aggregate and format the final response

Available agents:
- research: For information gathering, web search, document retrieval
- analysis: For data analysis, comparisons, insight generation
- writing: For text generation, summaries, reports

Respond with a plan in JSON format:
{
  "understanding": "Brief summary of user's request",
  "subtasks": [
    {"agent": "research", "task": "specific task description"},
    {"agent": "analysis", "task": "specific task description"},
    {"agent": "writing", "task": "specific task description"}
  ]
}
```

### 5.2 Research Agent

**System Prompt**:
```
You are a research specialist agent. Your capabilities include:
- Searching the web for current information
- Retrieving relevant documents from the knowledge base
- Summarizing and extracting key information

When researching:
1. Use web_search for current/recent information
2. Use document_search for internal knowledge
3. Synthesize findings into structured data

Always cite your sources and indicate confidence level.
```

**Plugins**:
- `web_search(query, max_results)`
- `document_search(query, limit)`

### 5.3 Analysis Agent

**System Prompt**:
```
You are an analysis specialist agent. Your capabilities include:
- Analyzing data and identifying patterns
- Comparing options and alternatives
- Generating insights and recommendations

When analyzing:
1. Structure the data clearly
2. Apply appropriate analytical frameworks
3. Provide evidence-based conclusions

Be objective and highlight trade-offs.
```

**Plugins**:
- `calculate(expression)`
- `compare(items, criteria)`

### 5.4 Writing Agent

**System Prompt**:
```
You are a writing specialist agent. Your capabilities include:
- Generating clear, well-structured text
- Creating summaries and reports
- Adapting tone and style for the audience

When writing:
1. Start with a clear structure
2. Use appropriate formatting
3. Be concise but comprehensive

Match the requested format (report, summary, email, etc.).
```

## 6. Plugins em Detalhe

### 6.1 WebSearchPlugin

```csharp
public class WebSearchPlugin
{
    private readonly BingSearchService _searchService;

    [KernelFunction("web_search")]
    [Description("Search the web for information on a topic")]
    public async Task<SearchResults> SearchAsync(
        [Description("The search query")] string query,
        [Description("Maximum results to return")] int maxResults = 5)
    {
        var results = await _searchService.SearchAsync(query, maxResults);
        return new SearchResults
        {
            Query = query,
            Items = results.Select(r => new SearchResult
            {
                Title = r.Title,
                Snippet = r.Snippet,
                Url = r.Url
            }).ToList()
        };
    }
}
```

### 6.2 DocumentPlugin

```csharp
public class DocumentPlugin
{
    private readonly IVectorStore _vectorStore;
    private readonly IEmbeddingService _embeddingService;

    [KernelFunction("document_search")]
    [Description("Search internal documents using semantic similarity")]
    public async Task<IEnumerable<DocumentResult>> SearchDocumentsAsync(
        [Description("The search query")] string query,
        [Description("Maximum documents")] int limit = 3)
    {
        var embedding = await _embeddingService.GetEmbeddingAsync(query);
        var documents = await _vectorStore.SearchAsync(embedding, limit);

        return documents.Select(d => new DocumentResult
        {
            Title = d.Title,
            Content = d.Content,
            Score = d.Score,
            Source = d.Source
        });
    }
}
```

## 7. APIs

### 7.1 Chat Endpoint

```
POST /api/chat
Content-Type: application/json

{
  "message": "Compare AWS, Azure and GCP for a SaaS startup",
  "sessionId": "optional-session-id",
  "stream": true
}

Response (streaming):
data: {"type": "thinking", "content": "Analyzing request..."}
data: {"type": "agent", "agent": "research", "status": "started"}
data: {"type": "agent", "agent": "research", "status": "completed"}
data: {"type": "content", "content": "Based on my analysis..."}
data: {"type": "done", "usage": {"tokens": 1234}}
```

### 7.2 Agents Endpoint

```
GET /api/agents

Response:
{
  "agents": [
    {
      "id": "orchestrator",
      "name": "Orchestrator Agent",
      "description": "Coordinates other agents",
      "capabilities": ["task_decomposition", "routing", "aggregation"]
    },
    {
      "id": "research",
      "name": "Research Agent",
      "description": "Information gathering specialist",
      "capabilities": ["web_search", "document_retrieval", "summarization"]
    }
  ]
}
```

## 8. Modelo de Dados

### 8.1 Conversation

```csharp
public class Conversation
{
    public string Id { get; set; }
    public string UserId { get; set; }
    public List<Message> Messages { get; set; }
    public DateTime CreatedAt { get; set; }
    public DateTime UpdatedAt { get; set; }
}

public class Message
{
    public string Id { get; set; }
    public MessageRole Role { get; set; } // User, Assistant, System
    public string Content { get; set; }
    public AgentMetadata? AgentMetadata { get; set; }
    public TokenUsage? Usage { get; set; }
    public DateTime Timestamp { get; set; }
}

public class AgentMetadata
{
    public string AgentId { get; set; }
    public List<string> PluginsUsed { get; set; }
    public Dictionary<string, object> Metadata { get; set; }
}
```

### 8.2 Agent Task

```csharp
public class AgentTask
{
    public string Id { get; set; }
    public string AgentId { get; set; }
    public string Description { get; set; }
    public TaskStatus Status { get; set; }
    public string? Input { get; set; }
    public string? Output { get; set; }
    public string? Error { get; set; }
    public TimeSpan Duration { get; set; }
    public TokenUsage Usage { get; set; }
}

public enum TaskStatus
{
    Pending,
    Running,
    Completed,
    Failed
}
```

## 9. Configuração

### 9.1 Azure OpenAI

```json
{
  "AzureOpenAI": {
    "Endpoint": "https://{resource}.openai.azure.com/",
    "ApiKey": "{key}",
    "Deployments": {
      "Chat": "gpt-4",
      "ChatFast": "gpt-35-turbo",
      "Embedding": "text-embedding-ada-002"
    }
  }
}
```

### 9.2 Agent Configuration

```json
{
  "Agents": {
    "Orchestrator": {
      "Model": "gpt-4",
      "MaxTokens": 2000,
      "Temperature": 0.3
    },
    "Research": {
      "Model": "gpt-35-turbo",
      "MaxTokens": 1500,
      "Temperature": 0.5
    },
    "Analysis": {
      "Model": "gpt-35-turbo",
      "MaxTokens": 1500,
      "Temperature": 0.3
    },
    "Writing": {
      "Model": "gpt-4",
      "MaxTokens": 3000,
      "Temperature": 0.7
    }
  }
}
```

---

*MORPH-SPEC by Polymorphism Tech*
