Skip to content

refactor(chat-agent): Introduce sub-agents for high-context tools #74

Closed

Description

@larryro

Problem

The current chat agent has 13 tools loaded directly, which causes two main issues:

  1. Context pollution - Tools like web_read, document parsing (pdf, docx, pptx), and integration can generate large outputs (20K-50K tokens for web pages, large document content, database query results). These accumulate in the main agent's context window, leading to:

    • Increased token usage and cost
    • Potential context overflow
    • Degraded performance as context grows
  2. Tool schema overhead - All 13 tool descriptions are included in every request, adding ~4,000-6,500 tokens to the system prompt even when most tools aren't needed.

Proposed Solution

Introduce 3 specialized sub-agents to handle high-context tools, following the existing workflow_assistant pattern:

Sub-Agent Tools Benefit
web_assistant web_read Isolates web page content (20K-50K tokens each)
document_assistant pdf, image, docx, pptx, generate_excel Isolates parsed document content + enables specialized instructions
integration_assistant integration, integration_introspect, verify_approval Isolates DB results + handles approval card linking

Direct tools (kept for fast response):

  • customer_read, product_read, rag_search, context_search - These have bounded output and are frequently used for simple queries.

Benefits

  1. Context isolation - Sub-agent context is discarded after use, only summarized result returns to main agent
  2. Faster simple queries - Direct tools remain fast without sub-agent overhead
  3. Better specialization - Each sub-agent can have domain-specific instructions
  4. Simpler maintenance - Isolated tool groups are easier to modify and test
  5. ~40-50% token savings on tool schema

Reference

Existing pattern: convex/agent_tools/sub_agents/workflow_assistant_tool.ts

Activity

  1. larryro commented on Jan 4, 2026

    @larryro
    ContributorAuthor

    Implementation Plan

    Overview

    Refactor the chat agent to delegate high-context tools to specialized sub-agents, following the existing workflow_assistant_tool.ts pattern.

    Goals:

    1. Context isolation - Prevent large tool outputs (web pages, documents, DB results) from polluting main agent context
    2. Improve specialization - Domain-specific instructions per agent
    3. Simplify maintenance - Isolated tool groups
    4. Keep simple tools fast - Direct access for bounded-output tools

    Current vs. Proposed Architecture

    Before (13 tools in chat agent)

    chat_agent
    ├── customer_read, product_read, rag_search
    ├── pdf, image, docx, pptx, generate_excel
    ├── integration, integration_introspect, verify_approval
    ├── workflow_assistant (existing sub-agent)
    ├── context_search
    └── web_read
    

    After (8 tools in chat agent)

    chat_agent
    ├── customer_read        (direct - bounded output, fast)
    ├── product_read         (direct - bounded output, fast)
    ├── rag_search           (direct - has top_k limit, fast)
    ├── context_search       (direct - needs thread access)
    ├── web_assistant        → delegates to: web_read (context isolation - web pages are 20K-50K tokens)
    ├── document_assistant   → delegates to: pdf, image, docx, pptx, generate_excel (context isolation + specialization)
    ├── integration_assistant → delegates to: integration, integration_introspect, verify_approval (context isolation + approval flow)
    └── workflow_assistant   (existing, unchanged)
    

    Token Savings: ~40-50% reduction in tool schema tokens


    New Sub-Agents (3 total)

    Sub-Agent Tools Model Max Steps Role Restriction Why Sub-Agent
    Web Assistant web_read OPENAI_MODEL 5 None Context isolation (web pages are huge)
    Document Assistant pdf, image, docx, pptx, generate_excel OPENAI_MODEL 15 None Context isolation + multi-step workflows
    Integration Assistant integration, integration_introspect, verify_approval OPENAI_MODEL 20 admin/developer Context isolation + approval card linking

    Implementation Steps

    Phase 1: Create Sub-Agent Factory Functions

    New files:

    1. convex/lib/create_web_agent.ts

      • Tools: web_read
      • Model: OPENAI_MODEL
      • maxSteps: 5
      • Focus: URL fetching, web search, content extraction, summarization
    2. convex/lib/create_document_agent.ts

      • Tools: pdf, image, docx, pptx, generate_excel
      • Model: OPENAI_MODEL
      • maxSteps: 15
      • Focus: File parsing, generation, template handling
    3. convex/lib/create_integration_agent.ts

      • Tools: integration, integration_introspect, verify_approval
      • Model: OPENAI_MODEL
      • maxSteps: 20
      • Focus: External system operations, approval workflows

    Phase 2: Create Sub-Agent Delegation Tools

    New files:

    1. convex/agent_tools/sub_agents/web_assistant_tool.ts

      args: z.object({
        userRequest: z.string(),
        url: z.string().optional(),
        searchQuery: z.string().optional(),
      })
    2. convex/agent_tools/sub_agents/document_assistant_tool.ts

      args: z.object({
        userRequest: z.string(),
        fileId: z.string().optional(),
        fileName: z.string().optional(),
      })
    3. convex/agent_tools/sub_agents/integration_assistant_tool.ts

      args: z.object({
        userRequest: z.string(),
        integrationName: z.string().optional(),
        operation: z.string().optional(),
      })
      • Must pass parentThreadId for approval card linking
      • Role restriction: admin/developer only

    Phase 3: Create Sub-Agent Instructions

    New files in convex/agent_tools/sub_agents/instructions/:

    1. web_instructions.ts - URL fetching, search optimization, content summarization
    2. document_instructions.ts - File format handling, template workflows
    3. integration_instructions.ts - Approval workflows, pre-validation

    Phase 4: Update Tool Registry

    Modify: convex/agent_tools/tool_registry.ts

    • Add new tool names: web_assistant, document_assistant, integration_assistant
    • Import and register new tools

    Phase 5: Update Chat Agent (Replace Tools)

    Modify: convex/lib/create_chat_agent.ts

    Before:

    const defaultToolNames: ToolName[] = [
      'rag_search',
      'web_read',               // → remove
      'pdf',                    // → remove
      'image',                  // → remove
      'generate_excel',         // → remove
      'docx',                   // → remove
      'pptx',                   // → remove
      'customer_read',
      'product_read',
      'workflow_assistant',
      'integration',            // → remove
      'integration_introspect', // → remove
      'verify_approval',        // → remove
    ];

    After:

    const defaultToolNames: ToolName[] = [
      // Direct tools (fast, bounded output)
      'customer_read',
      'product_read',
      'rag_search',
      'context_search',
      // Sub-agents (context isolation)
      'web_assistant',         // NEW - replaces web_read
      'document_assistant',    // NEW - replaces pdf, image, docx, pptx, generate_excel
      'integration_assistant', // NEW - replaces integration, integration_introspect, verify_approval
      'workflow_assistant',    // EXISTING
    ];

    Phase 6: Update Instructions & Test

    Update chat agent system instructions:

    1. Remove references to direct tool usage for web/document/integration operations
    2. Add guidance on when to use each sub-agent
    3. Clarify that sub-agents handle context-heavy operations

    Note: Keep original tools in the registry (sub-agents still use them). Only the chat agent's default tool selection changes.


    Key Design Decisions

    1. Sub-agents for high-context tools only - web_read, documents, integrations generate large outputs
    2. Direct tools stay fast - customer_read, product_read, rag_search have bounded output
    3. All sub-agents create sub-threads - Consistency with workflow_assistant pattern
    4. Keep context_search in main agent - Needs access to current thread ID
    5. Integration Assistant must pass parentThreadId - Required for approval card linking
    6. Integration Assistant role restriction - Restrict to admin/developer roles (writes to external systems)
    7. Direct replacement - No feature flag

    Files Summary

    Files to Modify (2)

    File Change
    convex/agent_tools/tool_registry.ts Add 3 new tool names and imports
    convex/lib/create_chat_agent.ts Replace 9 direct tools with 3 sub-agent tools

    Files to Create (9)

    File Purpose
    convex/lib/create_web_agent.ts Web Agent factory
    convex/lib/create_document_agent.ts Document Agent factory
    convex/lib/create_integration_agent.ts Integration Agent factory
    convex/agent_tools/sub_agents/web_assistant_tool.ts Web delegation tool
    convex/agent_tools/sub_agents/document_assistant_tool.ts Document delegation tool
    convex/agent_tools/sub_agents/integration_assistant_tool.ts Integration delegation tool
    convex/agent_tools/sub_agents/instructions/web_instructions.ts Web agent instructions
    convex/agent_tools/sub_agents/instructions/document_instructions.ts Document agent instructions
    convex/agent_tools/sub_agents/instructions/integration_instructions.ts Integration agent instructions

    Reference Pattern

    Follow the existing implementation in:

    • convex/agent_tools/sub_agents/workflow_assistant_tool.ts - Delegation tool pattern
    • convex/lib/create_workflow_agent.ts - Agent factory pattern

    Testing Checklist

    • Verify web_assistant correctly delegates to web_read
    • Verify document_assistant handles all file operations (pdf, image, docx, pptx, generate_excel)
    • Verify integration_assistant handles integrations with approval flow
    • Verify parentThreadId is correctly passed for approval card linking
    • Verify role restriction works for integration_assistant (admin/developer only)
    • Verify direct tools (customer_read, product_read, rag_search, context_search) still work fast
    • Verify no regression in existing workflow_assistant functionality
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    priority: medium

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions