Poetry Platform
Agentic Framework Architecture
AI-powered autonomous campaign management with multi-step reasoning,
human-in-the-loop escalation, and compliance-driven decision making.
What We Built
Four interconnected agentic capabilities for autonomous campaign management
๐
RIV-456
Daily Optimization
Automated bid and budget recommendations based on ROAS/CPA performance with dual-mode execution.
๐ค
RIV-457
Autonomous Executor
Full autonomous execution with mandatory validation, risk assessment, and HITL escalation.
๐ก๏ธ
RIV-458
Compliance Checker
Proactive validation against regulations, platform policies, and internal rules before execution.
๐ง
RIV-453
KB Tools Interface
OpenAI-compatible function schemas enabling Claude to query the Knowledge Base for context.
System Architecture
End-to-end flow from client request to execution
CLIENT
Poetry Web App
API Gateway
BPMN Workflows
โ
FUNCTIONS
Daily Optimization
Autonomous Executor
Compliance Checker
โ
AGENTIC CORE
ReAct Loop
Tool Dispatcher
HITL Manager
โ
KNOWLEDGE
KB Query Tool
KB Search Tool
Compliance Rules
Best Practices
โ
EVIDENCE
Audit Trail
CDD Compliance
Trace Correlation
ReAct Reasoning Loop
THINK โ ACT โ OBSERVE: The core pattern for autonomous decision-making
1. THINK
Analyze & Plan
โ
2. ACT
Execute Tool
โ
3. OBSERVE
Process Result
โ
Loop or
Complete
THINK Phase
- โClaude analyzes the current state and available information
- โDetermines what additional data is needed
- โSelects appropriate tool from available options
ACT Phase
- โCalls selected tool (KB query, metrics fetch, policy check)
- โStructured tool invocation with typed parameters
- โEvidence collected for audit trail
for iteration in range(config.max_iterations):
response = await claude.messages.create(messages, tools)
tool_result = await dispatch_tool(response.tool_use)
messages.append(tool_result)
RIV-456
Daily Optimization Agent
Dual-mode execution: Fast rule-based OR intelligent agentic reasoning
Sync Mode (Default)
Fast, deterministic optimization using rule-based logic:
- โROAS > 120% target + budget exhausted โ Increase budget 20%
- โROAS < 50% target โ Decrease bid 15% or pause
- โCPA > 150% target โ Decrease bid 20%
- โCPA < 70% target + good ROAS โ Increase bid 15%
Agentic Mode
Multi-step reasoning with tool access:
- โQueries KB for platform-specific best practices
- โFetches real-time metrics from ad platforms
- โValidates against OPA policies
- โCan request HITL for edge cases
AGENTIC_MODE = os.getenv("CORTEXONE_AGENTIC_MODE", "false").lower() == "true"
if AGENTIC_MODE:
return _optimize_daily_agentic(event, context)
else:
return _optimize_daily_sync(event)
RIV-457
Autonomous Executor
Full autonomous execution with mandatory validation and safety guardrails
1. Parse Request
โ
2. Gather Context (KB + Metrics)
โ
3. Compliance Validation
โ
4. Budget Validation
โ
5. Risk Assessment
โ
6. Execute or HITL Escalate
Key Safety Features
No Sync Fallback
Autonomous execution REQUIRES agentic mode. No shortcuts.
Mandatory Validation
All 5 validation steps must complete before execution.
Rollback Capability
Every executed action includes rollback metadata.
HITL Escalation Framework
Risk-based thresholds determine when human approval is required
Auto-Approve
- Budget impact < $1,000
- Change magnitude < 20%
- Action aligns with historical patterns
Proceed with Caution
- Budget impact $1,000 - $5,000
- Change magnitude 20% - 50%
- First-time action on campaign
Requires HITL
- Budget impact > $5,000
- Change magnitude > 50%
- Pause affecting >5 campaigns
- Policy violation detected
HIGH_RISK_BUDGET_THRESHOLD = 5000
HIGH_RISK_CHANGE_PERCENT = 50
if risk_level == "high":
return "HITL_REQUEST: Budget change of $12,500 exceeds threshold. Approve?"
RIV-458
Compliance Checker Agent
Proactive validation across three compliance domains
Regulatory Compliance
- GDPR - Data privacy
- CCPA - Consumer rights
- HIPAA - Healthcare
- SEC - Financial
- Geographic restrictions
Platform Policies
- Meta Advertising Policies
- Google Ads Policies
- TikTok Ad Policies
- LinkedIn Marketing
- Content restrictions
Internal Policies
- Budget approval thresholds
- Brand safety guidelines
- Audience restrictions
- Creative approvals
- Spend limits
Quick Check (Rule-Based)
Fast validation for common scenarios:
if 'alcohol' in content_categories:
if not has_age_restriction(21):
violations.append("AGE-ALCOHOL-US")
Full Check (Agentic)
Comprehensive multi-step validation:
compliance_context = {
'check_type': 'full',
'require_evidence': True,
'domains': ['regulatory', 'platform', 'internal']
}
RIV-453
Knowledge Base Tools Interface
OpenAI-compatible function schemas for seamless Claude integration
| Tool |
Purpose |
Key Parameters |
query_knowledge_base |
Natural language Q&A with RAG |
question, collection, include_sources |
search_knowledge_base |
Semantic similarity search |
query, limit, similarity_threshold |
get_compliance_rules |
Domain-specific compliance rules |
domain, platform, region |
get_platform_best_practices |
Platform optimization guidance |
platform, topic, campaign_type |
{
"tool_name": "query_knowledge_base",
"parameters": {
"question": "What are Meta's best practices for lookalike audiences?",
"collection": "poetry",
"include_sources": true
},
"persona": "campaign_manager",
"include_evidence": true,
"trace_id": "req-abc123"
}
Evidence Collection for CDD
Complete audit trail for Compliance-Driven Development
Evidence Metadata Structure
{
"evidence_id": "ev-abc123",
"timestamp": "2025-12-28T10:30:00Z",
"tool_name": "query_knowledge_base",
"query_hash": "sha256:a1b2c3...",
"persona": "campaign_manager",
"confidence": 0.92,
"sources": [...],
"trace_id": "req-xyz789"
}
Key Features
- โSHA-256 Query Hashing - Tamper-proof query verification
- โTrace Correlation - Links evidence across requests
- โSource Provenance - Document/chunk citations
- โConfidence Scores - Quantified reliability
- โPersona Context - Role-based filtering
Why Evidence Matters
๐
Audit Compliance
Complete decision trail for regulators
๐
Explainability
Understand why AI made decisions
๐
Reproducibility
Replay decisions for debugging
โ๏ธ
Accountability
Clear ownership of outcomes
Complete Request Flow
Example: Budget increase request through the agentic pipeline
Step 1
Request Received
Budget increase +25% for campaigns with high ROAS
โ
Step 2
Query KB
Fetch platform best practices for budget scaling
โ
Step 3
Fetch Metrics
Get current ROAS, CPA, spend from ad platforms
โ
Step 4
Compliance Check
Validate against budget policies, spending limits
โ
Step 5
Risk Assessment
Calculate risk level based on thresholds
โ
Step 6
Execute / HITL
Auto-execute or escalate based on risk
{
"action_type": "budget_increase",
"target_ids": ["campaign-001", "campaign-002"],
"parameters": {
"increase_percent": 25,
"reason": "High ROAS performance"
}
}
{
"execution_status": "executed",
"risk_assessment": {
"level": "medium",
"confidence": 0.88
},
"evidence": { ... }
}
RIV-454
Worker HITL + WebSocket Streaming
Real-time agent progress visibility with human intervention controls
WebSocket Streaming
- โexecution_started - Agent begins processing
- โstep_started/completed - Reasoning step progress
- โtool_called - Tool invocation with params/results
- โhuman_input_requested - HITL escalation
- โexecution_completed/failed - Final status
BaseAgenticWorker Features
- โExtended 120s timeout for multi-step execution
- โAutomatic lock extension to prevent task expiry
- โAgentTrace capture in process variables
- โHITL callback for human input requests
- โAuto-reconnection with exponential backoff
wsManager.on('tool_called', (event) => {
console.log(`Tool: ${event.toolName}`);
console.log(`Result: ${JSON.stringify(event.result)}`);
});
wsManager.on('human_input_requested', (event) => {
showHITLDialog(event.request);
});
RIV-459
Agent Progress Panel UI
Real-time visualization of agent reasoning with human intervention controls
๐
Live Step Visualization
Real-time display of observe/think/act/final phases with duration and token counts per step.
๐ ๏ธ
Tool Call Display
Expandable tool invocations showing parameters, results, and copy-to-clipboard functionality.
๐ค
Human Controls
Pause, resume, abort buttons plus context injection textarea for human guidance.
Component Architecture
AgentProgressPanel
Main container with WebSocket connection, progress bar, and controls
โ
AgentStepCard
Individual step with phase indicator and expandable content
โ
HITL Dialog
Text input or multiple choice for human responses
shadcn/ui
Card
Button
Progress
Alert
ScrollArea
Key Takeaways
What makes this architecture production-ready
Autonomous but Safe
ReAct reasoning enables complex decisions while HITL escalation ensures human oversight for high-risk actions.
Compliance-First
Every action validated against regulatory, platform, and internal policies before execution.
Evidence-Driven
Complete audit trail with query hashing, source provenance, and trace correlation for CDD compliance.
Knowledge-Powered
OpenAI-compatible KB interface enables Claude to access domain expertise during reasoning.
All Pull Requests (8 Total)
PR #413
Core Framework (RIV-452)
PR #418
Daily Optimization (RIV-456)
PR #419
Autonomous Executor (RIV-457)
PR #420
Compliance Checker (RIV-458)
PR #422
KB Tools Interface (RIV-453)
PR #423
Policy/Budget APIs (RIV-455)
PR #424
Progress Panel UI (RIV-459)
PR #425
Worker HITL (RIV-454)
EVOLUTION
Architecture Evolution: Build vs Buy
Why we built custom vs. using existing frameworks
| Framework |
ReAct |
HITL |
Streaming |
RAG |
BPMN |
Compliance |
| LangGraph |
โ
|
โ
Interrupts |
โ
|
โ
|
โ |
Limited |
| CrewAI |
โ
|
โ
human_input |
Limited |
โ
|
โ |
HIPAA/SOC2 |
| LlamaIndex |
โ
|
Limited |
โ
|
Best |
โ |
Limited |
| Claude Agent SDK |
โ
|
Custom |
Limited |
Limited |
โ |
Custom |
| Poetry (Rival) |
โ
|
โ
|
โ
|
โ
|
โ
|
CDD |
Key Differentiator: BPMN Integration
No existing framework supports BPMN/Camunda integration. This is core to Poetry's architecture - agents ARE Camunda external task workers with process variable capture, lock extension, and compliance audit trails.
SECURITY
MCP + mTLS Security Architecture
Enterprise-grade agent communication with mutual TLS
API Key Authentication (Current)
| Encryption | Via HTTPS |
| Client Identity | None (key only) |
| Key Theft | Single secret |
| Revocation | Hard |
| Audit | Which service? |
mTLS Authentication (Target)
| Encryption | Via TLS |
| Client Identity | Certificate |
| Cert Theft | Need cert + key |
| Revocation | Easy (CRL/OCSP) |
| Audit | Certificate identifies |
context = ssl.create_default_context(ssl.Purpose.SERVER_AUTH)
context.load_cert_chain(
certfile="/etc/certs/agent-client.pem",
keyfile="/etc/certs/agent-client.key"
)
context.load_verify_locations("/etc/certs/ca.pem")
context.verify_mode = ssl.CERT_REQUIRED
MODELER
Custom BPMN Task Types
Visual differentiation for Agentic Tasks and Rival Functions
[A]
Daily Optimization
โ๏ธ
Agentic Task
Multi-step reasoning with HITL
[F]
Predictive Engine
โ๏ธ
Rival Function
CortexOne function invocation
Popup Menu
Custom entries in "Change element" menu with Rival section separator
Visual Badges
Purple [A] for Agentic, Blue [F] for Functions - instant recognition
Properties Panel
Context-aware panels with agent config, tools, HITL settings
VISUALIZATION
Agent Execution Visualizer
Real-time observation of agent reasoning and tool calls
๐ค Daily Optimization Agent
โฑ๏ธ 47s / 120s
REASONING
"Analyzing campaign performance data to determine if budget increase is justified..."
TOOL CALLS
โ
query_knowledge_base 1.2s
Server: knowledge-base (MCP/mTLS)
โ
fetch_campaign_metrics 3.4s
Server: predictive-engine (Rival Function)
โณ validate_policy running...
Server: policy-service (MCP/mTLS)
CONFIDENCE โโโโโโโโโโ 68%
EVIDENCE ๐ 3 docs ยท ๐ 7 days
WebSocket Streaming
Real-time Updates
Tool Call Tracking
Confidence Meter
ARCHITECTURE
Target Architecture
Unified Agentic Platform with MCP Gateway
MODELER
[A] Agentic Task
[F] Rival Function
Properties Panel
โ Deploy
ENGINE
Camunda (BPMN)
External Tasks
Process Variables
โ External Task
WORKER
Unified Worker
AgenticStrategy
FunctionStrategy
โ MCP/mTLS
GATEWAY
MCP Gateway
Agent Registry
Health Tracking
โ
AGENTS
Claude SDK
KB Server
Policy Service
Rival Functions
Implementation Roadmap
Phased delivery with working reference implementation
Stream 1
BPMN Modeler
- RivalPopupMenuProvider
- RivalRenderer (badges)
- Properties Panels
- Combined RivalPalette
Stream 2
Visualization
- AgentExecutionVisualizer
- ToolCallCard
- ExecutionTimeline
- ConfidenceMeter
Stream 3
Backend
- Claude Agent SDK
- MCP Gateway + mTLS
- Agent Registry
- Unified Worker
Reference Implementation Goal
๐
Define
Create tasks in modeler
๐
Deploy
Deploy to Camunda
โถ๏ธ
Execute
Run end-to-end
๐๏ธ
Observe
Watch in visualizer