Building an AI Chief of Staff with Cortex - n8n with NLP
Guide to creating an autonomous AI that orchestrates actions across all workplace applications using Cortex’s function-calling capabilities.
Status: This guide is in progress.
This guide walks you through designing an AI Chief of Staff—an AI version of n8n—powered by Cortex. Instead of only answering questions, this assistant can take actions across every app in your workspace by selecting and executing the correct function at the right time.
Note: All code examples in this guide are for demonstration purposes. They show the concepts and patterns you can use when building your own Glean-like application with Cortex APIs. Follow the actual API documentation to adapt these examples to your specific use case, technology stack, and requirements.
Goal: Let any agent ask Cortex “What should I do next?” and receive a structured function call (plus parameters) that your execution layer can run.
The “Second Brain” Concept
Think of Cortex as your AI agent’s second brain—a reasoning layer that transforms natural language requests into precise function calls. Your primary AI agent handles conversation and context, while Cortex becomes the function selection oracle that knows:
- Which function to call for any given task
- When multiple functions need to be chained together
- How to adapt based on user preferences and historical patterns
- Why certain approaches work better for specific users or scenarios
This separation of concerns means your AI agent doesn’t need to maintain complex decision trees or hardcoded workflows. Instead, it can focus on understanding user intent while delegating the “how to execute” decisions to Cortex’s reasoning engine.
The Power of Intelligent Function Routing
Unlike traditional automation platforms where you build rigid if-then workflows, Cortex enables dynamic function routing. Your AI agent can say:
“The user wants to ‘prepare for tomorrow’s client meeting’—what should I do?”
Cortex responds with context-aware suggestions:
- Check calendar for meeting details
- Pull recent communication threads with that client
- Generate briefing notes from CRM data
- Set up the meeting room technology
- Send agenda reminders to participants
The same request from different users might yield different function sequences based on their roles, preferences, and historical patterns—all automatically determined by Cortex’s reasoning layer.
Why an AI Chief of Staff?
- Unified Automation: Replace brittle manual workflows with a single reasoning layer.
- Context-Aware: Decisions include user preferences, company policies, and real-time data.
- Incremental Roll-Out: Start with read-only automations, graduate to high-impact write actions.
- Agent Enhancement: Transform any AI agent into an action-capable assistant without rebuilding core logic.
Architecture Overview
- Action Orchestrator: Your runtime that receives function suggestions from Cortex and executes them.
- Cortex: Stores function definitions & performs reasoning to decide which function (if any) solves the task.
- Workspace Apps: Anything with an API—CRM, calendar, ticketing, HRIS.
How Cortex Essential Features Enable This
AI Memories for Function Learning
Cortex’s AI Memories don’t just remember user preferences—they learn function effectiveness patterns. When a user frequently chooses certain functions for specific types of tasks, Cortex builds a personalized “function preference profile.” This means your AI agent gets smarter suggestions over time without any manual training.
Example: If Sarah always prefers Slack notifications over email for urgent updates, Cortex learns this pattern and automatically suggests send_slack_message
instead of send_email
for her urgent notifications.
Multi-Step Reasoning for Complex Workflows
Simple tasks require one function call. Complex business processes require orchestrated sequences. Cortex’s multi-step reasoning automatically decomposes requests like “Onboard the new hire” into:
- Create accounts across systems
- Send welcome materials
- Schedule orientation meetings
- Assign equipment requests
- Notify team members
Your AI agent makes one request to Cortex and receives a complete execution plan with dependency management built-in.
Self-Improving Function Selection
As your function library grows and usage patterns emerge, Cortex’s self-improving capabilities automatically optimize function selection. It learns which functions tend to succeed together, which ones cause errors in certain contexts, and how to adapt suggestions based on real-world outcomes.
This means your AI Chief of Staff becomes more reliable over time without manual tuning—it develops institutional knowledge about what works in your specific environment.
Multi-Tenant Function Isolation
Different teams, departments, or customers need access to different function sets. Cortex’s multi-tenant architecture ensures that your sales team’s AI agent only sees sales-related functions, while the engineering team’s agent has access to deployment and monitoring functions.
This isn’t just about security—it’s about cognitive focus. By limiting function scope per context, Cortex can make more precise recommendations without being overwhelmed by irrelevant options.
Step 1 — Define & Register Functions
1.1 Function Schema
Cortex treats each callable as a knowledge object. The minimal schema:
1.2 Upload to Cortex
Use the same /upload/upload_app_sources
endpoint you already know—set type: "function"
.
Tip: Keep function descriptions natural-language and goal-oriented—Cortex uses them during reasoning.
1.3 Versioning & Deprecation
Store new versions with id: functionName_v2
. Mark old versions’ cortex_metadata.deprecated = true
so Cortex avoids suggesting them.
Step 2 — Build the Action Orchestrator
The orchestrator bridges Cortex ↔ real APIs.
Notable Flags
auto_agent_routing
: Lets Cortex choose between answering vs acting.multi_step_reasoning
: Enables plans like “create Zoom, then email invite”.
Real-World Applications
Customer Success Automation
Scenario: A customer submits a support ticket asking for a feature demo.
Traditional Approach: Support agent manually coordinates with sales, schedules demo, updates CRM, sends confirmations.
AI Chief of Staff Approach: Your AI agent tells Cortex “Customer Jane from Acme Corp wants a demo of our new reporting feature.”
Cortex suggests:
check_customer_tier
→ Determines appropriate demo levelfind_available_demo_slots
→ Checks AE calendar availabilitycreate_demo_meeting
→ Books calendar event with zoom linkupdate_crm_opportunity
→ Logs demo request and scheduled datesend_confirmation_email
→ Notifies customer with details
All triggered by one natural language request, all personalized to Jane’s account context.
Executive Assistant Workflows
Scenario: CEO says “Prepare for board meeting next Tuesday”
Without hardcoding what “prepare” means, Cortex can suggest:
compile_kpi_dashboard
→ Gather latest metricsreview_action_items
→ Check previous meeting follow-upsbook_catering
→ Arrange refreshments based on attendee countsend_agenda_reminder
→ Notify board members 24 hours priorprepare_presentation_materials
→ Compile slide deck from templates
The beauty is that each executive’s “preparation” style is different—Cortex learns these patterns through AI Memories and adapts accordingly.
DevOps Incident Response
Scenario: Monitoring alert triggers: “Database response time degraded”
Your AI agent asks Cortex for the appropriate response. Based on severity, time of day, and historical patterns, Cortex might suggest:
During business hours:
create_incident_ticket
→ Log in tracking systemnotify_oncall_engineer
→ Alert via PagerDutyscale_database_resources
→ Auto-remediation attemptpost_status_update
→ Inform stakeholders
During off-hours for minor issues:
log_incident_details
→ Document for morning reviewmonitor_for_escalation
→ Set up enhanced alertingschedule_followup_review
→ Add to next team standup
Same trigger, different responses based on learned patterns and context.
Step 3 — Event & Trigger Model
Your Chief of Staff should react to:
- Direct Commands – “Book me a 30-min call with Alice next week.”
- Scheduled Jobs – Daily stand-up summary at 9 AM.
- System Events – New ticket in Jira → triage.
Create a thin wrapper per event source that forwards the natural-language description to the orchestrator.
Step 4 — Planning & Multi-Step Execution
Sometimes the task requires multiple calls.
- Plan Generation: Ask Cortex “return a JSON array of functions to execute sequentially.”
- Dependency Resolution: Inject outputs of earlier steps into later ones.
- Rollback / Compensation: If step n fails, undo steps ≤ n-1.
Leveraging Cortex’s Retrieval Capabilities
Your function library becomes part of Cortex’s knowledge base. This means function selection isn’t just based on keywords—it’s semantic understanding.
When a user says “I need to tell the team about the delay,” Cortex understands this could map to:
send_slack_announcement
for immediate updatesupdate_project_timeline
for formal documentationschedule_team_meeting
for complex discussionssend_client_notification
if external communication is needed
The retrieval engine finds semantically similar past requests and suggests functions that worked well in those contexts, even if the exact wording was different.
Context-Aware Function Metadata
Use Cortex’s metadata filtering to make function suggestions context-aware:
When a finance manager requests expense approval during business hours, Cortex automatically considers these constraints in its function selection logic.
Step 5 — Security, Auth & Governance
- OAuth Vault: Store per-user tokens; Orchestrator injects correct token at runtime.
- Policy Engine: Prevent ""delete all records” unless requester ∈
admins
. - Approval Workflow: For risky actions, route through Slack message “Approve / Reject”.
- Audit Log: Persist
task → function → result
for compliance.
Step 6 — Observability & Self-Improvement
Metric | Why it matters |
---|---|
Suggested → Executed ratio | High ratio = Cortex understands tasks |
Average time-to-completion | Spot slow external APIs |
Rollback frequency | Detect unstable functions |
Auto-tune by feeding metrics back to Cortex’s memory:
The Compound Effect of AI Memories + Function Selection
As your AI Chief of Staff runs more tasks, something powerful happens: Cortex builds institutional knowledge about how work gets done in your organization.
It learns that:
- Marketing requests usually need design review before execution
- Engineering deployments require specific approval chains
- Customer success follows different escalation paths per account tier
- Executive requests often have implicit urgency requirements
This knowledge gets encoded in AI Memories and influences future function suggestions. Your AI agent becomes not just capable of executing tasks, but wise about how to execute them well in your specific context.
Function Composition Patterns
Over time, Cortex identifies function composition patterns—sequences of functions that frequently work well together. These emerge organically from usage data rather than manual programming:
gather_data
→generate_report
→schedule_review_meeting
detect_anomaly
→investigate_root_cause
→implement_fix
→verify_resolution
receive_lead
→qualify_prospect
→assign_sales_rep
→schedule_discovery_call
Your AI agent can reference these learned patterns when planning complex workflows, making it more effective at orchestrating sophisticated business processes.
Best Practices Checklist
- Write precise descriptions; mention side-effects.
- Group functions into collections (
billing
,hr
,sales
). - Start read-only (analytics) before enabling write.
- Use idempotent APIs or implement retries with back-off.
- Maintain simulated staging workspace for testing.
- Leverage AI Memories to personalize function selection over time.
- Use multi-step reasoning for complex business processes.
- Implement metadata filtering for context-aware suggestions.
- Feed execution results back to Cortex for self-improvement.
Next Steps
- Pick one app (e.g., Slack) and register 3–5 high-value actions.
- Build a CLI wrapper around the orchestrator for local experiments.
- Roll out to a friendly internal team, gather feedback, iterate.
Your AI Chief of Staff will evolve organically—each new function expands its capabilities, and Cortex’s reasoning ensures the right action is chosen at the right moment. The result is an AI agent that doesn’t just follow scripts, but thinks intelligently about how to help users accomplish their goals.