Skip to main content

AI Agent System Guide

Master OpsHub’s sophisticated multi-agent AI system designed specifically for investment operations. This guide covers everything from basic agent interactions to advanced orchestration patterns.

System Architecture

OpsHub’s agent system is built on LangGraph, providing a robust framework for multi-agent collaboration:

Available Agents

1. Orchestrator Agent

The central coordinator that manages all other agents:
The Orchestrator is your primary interface - it understands context and automatically delegates to specialized agents
Capabilities:
  • Task decomposition and planning
  • Agent selection and coordination
  • Context management across sessions
  • Result synthesis and presentation
  • Error handling and recovery
Example Interaction:
# Python SDK example
from opshub import OrchestratorAgent

agent = OrchestratorAgent(api_key="YOUR_KEY")
response = await agent.query(
    "Calculate NAV for Fund XYZ and check for compliance breaches",
    context={"fund_id": "xyz_123", "date": "2024-10-30"}
)

2. Specialized Agents

  • Financial Operations
  • Analytics & Data
  • Compliance & Risk
  • Technical Operations
Fund Accountant Agent
  • NAV calculations and validation
  • Fee computation and accruals
  • Income and expense allocation
  • Capital activity processing
Portfolio Manager Agent
  • Position tracking and analysis
  • Performance attribution
  • Rebalancing recommendations
  • Risk-adjusted returns calculation

3. Ambient Monitor

Continuous background monitoring agent:
  • Real-time anomaly detection
  • Threshold breach alerts
  • Pattern recognition
  • Predictive warnings
  • System health monitoring

Agent Communication Patterns

Synchronous Communication

For immediate responses and interactive sessions:
// TypeScript example
import { AgentClient } from '@opshub/agents';

const client = new AgentClient({
  endpoint: 'wss://api.opshub.nomark.ai/agents',
  apiKey: process.env.OPSHUB_API_KEY
});

// Direct agent communication
const response = await client.query({
  agent: 'fund_accountant',
  action: 'calculate_nav',
  params: {
    fundId: 'FUND001',
    valuationDate: '2024-10-30'
  }
});

Asynchronous Communication

For long-running operations:
// Submit async job
const job = await client.submitJob({
  agent: 'risk_analyst',
  action: 'run_stress_test',
  params: {
    portfolio: 'PORTFOLIO001',
    scenarios: ['market_crash', 'interest_rate_spike']
  }
});

// Check status
const status = await client.getJobStatus(job.id);

// Retrieve results when complete
if (status.state === 'completed') {
  const results = await client.getJobResults(job.id);
}

Event-Driven Communication

Subscribe to agent events:
// Subscribe to events
client.subscribe('compliance_sentinel', (event) => {
  if (event.type === 'breach_detected') {
    console.log('Compliance breach:', event.details);
    // Trigger automated response
  }
});

Context Management

Session Context

Maintain context across interactions:
# Create context-aware session
session = agent.create_session(
    workspace_id="WORKSPACE001",
    user_id="USER123",
    context={
        "default_fund": "FUND001",
        "reporting_currency": "USD",
        "compliance_regime": "SEC"
    }
)

# All queries in session maintain context
response1 = await session.query("Show me today's positions")
response2 = await session.query("Calculate VaR")  # Uses positions from previous query

Workspace Context

Share context across team members:
# Set workspace-level context
workspace = agent.workspace("WORKSPACE001")
workspace.set_context({
    "fiscal_year_end": "12-31",
    "accounting_basis": "GAAP",
    "default_benchmarks": ["SPX", "AGG"]
})

Tool Integration

Agents have access to specialized tools:
  • SQL query execution
  • DataFrame operations
  • Time series analysis
  • Data transformation
  • Financial calculations
  • Statistical functions
  • Risk metrics
  • Performance analytics
  • API connectors
  • File parsers
  • Email handlers
  • FTP/SFTP clients
  • Report generation
  • Chart creation
  • Excel automation
  • PDF creation

Advanced Features

Multi-Agent Collaboration

Complex tasks automatically trigger multi-agent collaboration:
# Complex request triggering multiple agents
result = await orchestrator.execute(
    "Prepare month-end reports for all funds with variance analysis and compliance check"
)

# Behind the scenes:
# 1. Fund Accountant calculates NAVs
# 2. Investment Analytics performs variance analysis
# 3. Compliance Sentinel checks regulations
# 4. Dashboard Architect creates visualizations
# 5. Orchestrator synthesizes results

Custom Agent Development

Extend the system with custom agents:
from opshub.agents import CustomAgent, Tool

class TaxOptimizationAgent(CustomAgent):
    name = "tax_optimizer"
    description = "Optimizes portfolio for tax efficiency"

    tools = [
        Tool("calculate_tax_liability"),
        Tool("identify_harvesting_opportunities"),
        Tool("simulate_tax_strategies")
    ]

    async def process(self, request):
        # Custom logic here
        return optimization_results

Agent Learning & Improvement

Agents continuously improve through:
  • Feedback loops from user interactions
  • Pattern recognition from historical data
  • Model fine-tuning on domain-specific data
  • A/B testing of different approaches

Performance Optimization

Caching Strategies

# Enable semantic caching
agent.configure({
    "cache_enabled": True,
    "cache_ttl": 3600,
    "cache_similarity_threshold": 0.95
})

Parallel Processing

# Parallel agent execution
tasks = [
    orchestrator.query_async("Calculate NAV for Fund A"),
    orchestrator.query_async("Calculate NAV for Fund B"),
    orchestrator.query_async("Calculate NAV for Fund C")
]

results = await asyncio.gather(*tasks)

Resource Management

# Configure resource limits
agent.set_limits({
    "max_tokens": 4000,
    "timeout": 30,
    "max_retries": 3,
    "rate_limit": 100  # requests per minute
})

Monitoring & Observability

Agent Metrics

Monitor agent performance:
metrics = agent.get_metrics()
print(f"Response time: {metrics.avg_response_time}ms")
print(f"Success rate: {metrics.success_rate}%")
print(f"Token usage: {metrics.total_tokens}")

Audit Trail

Track all agent interactions:
# Retrieve audit logs
logs = agent.get_audit_logs(
    start_date="2024-10-01",
    end_date="2024-10-30",
    agent="compliance_sentinel"
)

Health Checks

# Check agent health
health = agent.health_check()
for agent_name, status in health.items():
    print(f"{agent_name}: {status.state} - {status.latency}ms")

Security & Compliance

Authentication

# API key authentication
agent = OrchestratorAgent(
    api_key="YOUR_API_KEY",
    api_secret="YOUR_SECRET"
)

# OAuth 2.0
agent = OrchestratorAgent(
    oauth_token="YOUR_OAUTH_TOKEN"
)

Data Privacy

  • End-to-end encryption for sensitive data
  • PII masking and redaction
  • Data residency compliance
  • Right to be forgotten support

Access Control

# Role-based access
agent.set_permissions({
    "role": "analyst",
    "allowed_agents": ["investment_analytics", "portfolio_manager"],
    "restricted_actions": ["delete", "modify_critical"]
})

Troubleshooting

If agents are not responding as expected, check the troubleshooting guide below

Common Issues

Symptoms: Agent doesn’t respond within expected timeSolutions:
  • Increase timeout settings
  • Break complex queries into smaller tasks
  • Check network connectivity
  • Verify API rate limits
Symptoms: Agent doesn’t remember previous interactionsSolutions:
  • Ensure session management is enabled
  • Check context TTL settings
  • Verify memory store connectivity
  • Review context size limits
Symptoms: Agent provides inaccurate informationSolutions:
  • Verify data source accuracy
  • Check agent configuration
  • Review prompt engineering
  • Enable verbose logging

Best Practices

Clear Instructions

Provide specific, unambiguous requests to agents

Context Setting

Set appropriate context at session start

Error Handling

Implement robust error handling and retries

Monitor Usage

Track token usage and optimize queries

Next Steps


Pro Tip: Start with the Orchestrator Agent for most tasks - it automatically determines which specialized agents to engage based on your request.