byterover-cli icon indicating copy to clipboard operation
byterover-cli copied to clipboard

Add Vertex AI to Cipher as part of LLM Config

Open billcache opened this issue 1 year ago • 0 comments

1. Overview

Brief Summary: This architecture defines the integration of Google Cloud Vertex AI into Cipher's LLM service ecosystem, providing enterprise-grade AI capabilities with regional endpoints, advanced authentication, and seamless tool calling support while maintaining consistency with existing provider patterns.

2. Guiding Principles / Design Philosophy

Core Architectural Principles:

  • Modularity: Vertex AI service follows the established ILLMService interface pattern
  • Consistency: Maintains the same API patterns as existing providers (OpenAI, Anthropic)
  • Extensibility: Designed to support future Google Cloud AI services
  • Security: Enterprise-grade authentication with service account and API key support
  • Reliability: Robust error handling and retry logic for production environments
  • Performance: Regional endpoint optimization and intelligent caching
  • Maintainability: Follows existing code patterns and testing standards

Why These Principles Matter: Vertex AI integration must seamlessly fit into Cipher's existing architecture while providing enterprise-grade capabilities. The modular approach ensures that adding Vertex AI doesn't break existing functionality, while the consistency principle ensures developers can easily switch between providers. The security and reliability principles are critical for enterprise deployments where Vertex AI is commonly used.

3. High-Level Architecture Diagram (Conceptual)

┌─────────────────────────────────────────────────────────────────┐
│                    Cipher LLM Service Layer                    │
├─────────────────────────────────────────────────────────────────┤
│  ┌─────────────┐  ┌─────────────┐  ┌─────────────┐          │
│  │   OpenAI    │  │  Anthropic  │  │  Vertex AI  │  ← NEW   │
│  │   Service   │  │   Service   │  │   Service   │          │
│  └─────────────┘  └─────────────┘  └─────────────┘          │
│         │                │                │                  │
│         └────────────────┼────────────────┘                  │
│                          │                                   │
├──────────────────────────┼───────────────────────────────────┤
│                    Service Factory                           │
│  ┌─────────────────────────────────────────────────────────┐  │
│  │  createLLMService() - Provider Selection Logic        │  │
│  │  • OpenAI/OpenRouter → OpenAIService                  │  │
│  │  • Anthropic → AnthropicService                       │  │
│  │  • Vertex AI → VertexAIService ← NEW                  │  │
│  └─────────────────────────────────────────────────────────┘  │
├─────────────────────────────────────────────────────────────────┤
│                    Configuration Layer                        │
│  ┌─────────────────────────────────────────────────────────┐  │
│  │  LLMConfigSchema + Vertex AI Fields                   │  │
│  │  • projectId (required)                               │  │
│  │  • location (required)                                │  │
│  │  • apiKey (optional)                                  │  │
│  │  • serviceAccountKey (optional)                       │  │
│  └─────────────────────────────────────────────────────────┘  │
├─────────────────────────────────────────────────────────────────┤
│                    Authentication Layer                       │
│  ┌─────────────────────────────────────────────────────────┐  │
│  │  Google Cloud Auth Strategies                          │  │
│  │  • API Key Authentication                             │  │
│  │  • Service Account Authentication                      │  │
│  │  • Application Default Credentials                     │  │
│  └─────────────────────────────────────────────────────────┘  │
├─────────────────────────────────────────────────────────────────┤
│                    Tool Integration Layer                     │
│  ┌─────────────────────────────────────────────────────────┐  │
│  │  UnifiedToolManager + Vertex AI Support               │  │
│  │  • formatToolsForVertexAI()                          │  │
│  │  • OpenAI-compatible function calling                 │  │
│  │  • Tool execution routing                             │  │
│  └─────────────────────────────────────────────────────────┘  │
└─────────────────────────────────────────────────────────────────┘

Explanation: The architecture shows how Vertex AI integrates into Cipher's existing LLM service ecosystem. The new VertexAIService follows the same interface as existing providers, while the service factory handles provider selection and initialization. The configuration layer extends to support Vertex AI-specific fields, and the authentication layer supports Google Cloud's multiple auth strategies. The tool integration layer ensures Vertex AI can use the same tools as other providers.

4. Detailed Component Breakdown

4.1 Core Service Components

VertexAIService (src/core/brain/llm/services/vertex-ai.ts)

  • Location: src/core/brain/llm/services/vertex-ai.ts
  • Role/Purpose: Primary service implementing Vertex AI integration
  • Key Responsibilities:
    • Implements ILLMService interface
    • Handles Vertex AI API communication
    • Manages authentication and regional endpoints
    • Processes tool calling and responses
    • Implements retry logic and error handling
  • Interfaces/APIs:
    • Implements ILLMService interface
    • Exposes generate(), directGenerate(), getAllTools(), getConfig()
  • Dependencies:
    • @google-cloud/aiplatform SDK
    • google-auth-library for authentication
    • ContextManager for conversation history
    • UnifiedToolManager or MCPManager for tool execution
  • Impact on Existing System: Extends existing service ecosystem without breaking changes

Vertex AI Configuration Schema (src/core/brain/llm/config.ts)

  • Location: src/core/brain/llm/config.ts (extended)
  • Role/Purpose: Defines Vertex AI-specific configuration validation
  • Key Responsibilities:
    • Validates Vertex AI configuration fields
    • Ensures required fields (projectId, location) are present
    • Handles authentication method selection
    • Provides default values and validation
  • Interfaces/APIs:
    • Extends LLMConfigSchema with Vertex AI fields
    • Provides type-safe configuration interface
  • Dependencies:
    • Zod schema validation
    • Environment variable handling
  • Impact on Existing System: Additive changes to existing config schema

Vertex AI Factory Integration (src/core/brain/llm/services/factory.ts)

  • Location: src/core/brain/llm/services/factory.ts (extended)
  • Role/Purpose: Creates and configures Vertex AI service instances
  • Key Responsibilities:
    • Initializes Vertex AI SDK with proper authentication
    • Configures regional endpoints and project settings
    • Handles service account vs API key authentication
    • Creates VertexAIService instances with dependencies
  • Interfaces/APIs:
    • Extends _createLLMService() function
    • Handles Vertex AI provider case
  • Dependencies:
    • @google-cloud/aiplatform SDK
    • google-auth-library
    • Existing factory patterns
  • Impact on Existing System: Additive case in existing factory switch statement

4.2 Authentication Components

Google Cloud Authentication Manager (src/core/brain/llm/services/vertex-ai-auth.ts)

  • Location: src/core/brain/llm/services/vertex-ai-auth.ts
  • Role/Purpose: Manages Google Cloud authentication strategies
  • Key Responsibilities:
    • Handles API key authentication
    • Manages service account authentication
    • Supports Application Default Credentials
    • Provides authentication token management
  • Interfaces/APIs:
    • authenticateWithApiKey(apiKey: string)
    • authenticateWithServiceAccount(serviceAccountKey: string)
    • authenticateWithDefaultCredentials()
  • Dependencies:
    • google-auth-library
    • @google-cloud/aiplatform
  • Impact on Existing System: New component for Google Cloud auth patterns

4.3 Tool Integration Components

Vertex AI Tool Formatter (src/core/brain/tools/unified-tool-manager.ts)

  • Location: src/core/brain/tools/unified-tool-manager.ts (extended)
  • Role/Purpose: Formats tools for Vertex AI function calling
  • Key Responsibilities:
    • Converts tools to Vertex AI function calling format
    • Handles tool parameter validation
    • Ensures compatibility with Vertex AI API
  • Interfaces/APIs:
    • formatToolsForVertexAI(tools: CombinedToolSet): any[]
    • Extends getToolsForProvider() method
  • Dependencies:
    • Existing UnifiedToolManager
    • Tool parameter schemas
  • Impact on Existing System: Additive method in existing tool manager

4.4 Environment Configuration Components

Vertex AI Environment Variables (src/core/env.ts)

  • Location: src/core/env.ts (extended)
  • Role/Purpose: Manages Vertex AI environment configuration
  • Key Responsibilities:
    • Defines Vertex AI environment variables
    • Provides type-safe environment access
    • Handles default values and validation
  • Interfaces/APIs:
    • VERTEX_AI_PROJECT_ID
    • VERTEX_AI_LOCATION
    • VERTEX_AI_API_KEY
    • VERTEX_AI_SERVICE_ACCOUNT_KEY
  • Dependencies:
    • Existing environment schema
    • Zod validation
  • Impact on Existing System: Additive environment variables

5. Key Interactions and Data Flow (Walkthroughs)

5.1 Vertex AI Service Initialization Flow

1. User Configuration → LLMConfig with provider: 'vertex-ai'
2. Factory Selection → _createLLMService() detects 'vertex-ai' case
3. Authentication Setup → GoogleCloudAuthManager.authenticate()
4. SDK Initialization → new PredictionServiceClient()
5. Service Creation → new VertexAIService(client, config)
6. Tool Integration → UnifiedToolManager.getToolsForProvider('vertex-ai')
7. Ready State → Service ready for generate() calls

5.2 Vertex AI Tool Calling Flow

1. User Input → VertexAIService.generate(userInput)
2. Context Preparation → ContextManager.getFormattedMessage()
3. Tool Formatting → UnifiedToolManager.formatToolsForVertexAI()
4. API Call → PredictionServiceClient.predict()
5. Function Call Detection → Parse response for function calls
6. Tool Execution → UnifiedToolManager.executeTool()
7. Result Processing → ContextManager.addToolResult()
8. Response Generation → Return tool results or direct answer

5.3 Authentication Flow

1. Configuration Check → Validate projectId and location
2. Auth Method Selection → API key vs service account
3. Credential Creation → GoogleAuth.createCredentials()
4. Client Initialization → PredictionServiceClient with auth
5. Connection Test → Validate API access
6. Service Ready → Authenticated service ready for use

6. Cross-Cutting Concerns / Non-Functional Requirements

6.1 Error Handling Strategy

  • Retryable Errors: Rate limits (429), temporary failures (500, 502, 503, 504)
  • Non-Retryable Errors: Authentication failures, invalid project/location, quota exceeded
  • Error Mapping: Map Vertex AI errors to consistent Cipher error format
  • Logging: Comprehensive error logging with context and retry attempts

6.2 Configuration Management

  • Environment Variables: Support for all Vertex AI configuration via environment
  • Validation: Zod schema validation for all Vertex AI config fields
  • Defaults: Sensible defaults for location and authentication methods
  • Secrets Management: Secure handling of API keys and service account credentials

6.3 Scalability Considerations

  • Regional Endpoints: Automatic routing to nearest Vertex AI region
  • Connection Pooling: Reuse authenticated clients for performance
  • Caching: Intelligent caching of authentication tokens and model metadata
  • Load Balancing: Support for multiple Vertex AI projects/regions

6.4 Security Implementation

  • API Key Security: Secure storage and transmission of API keys
  • Service Account Security: Secure handling of service account JSON
  • Network Security: TLS encryption for all Vertex AI API calls
  • Access Control: Project-level access control and IAM integration

6.5 Observability Strategy

  • Logging: Structured logging for all Vertex AI operations
  • Metrics: Performance metrics for API calls and tool execution
  • Tracing: Request tracing for debugging and performance analysis
  • Monitoring: Health checks for Vertex AI service availability

6.6 Testing Strategy

  • Unit Tests: Test VertexAIService methods in isolation
  • Integration Tests: Test full Vertex AI API integration
  • Mock Testing: Mock Vertex AI API responses for reliable testing
  • Authentication Tests: Test all authentication methods
  • Tool Integration Tests: Test tool calling with Vertex AI

7. Implementation Guidelines / Best Practices

7.1 Code Standards

  • Follow existing TypeScript patterns in Cipher
  • Use consistent error handling patterns from other services
  • Implement comprehensive logging with structured data
  • Follow existing naming conventions and file organization

7.2 Design Patterns

  • Factory Pattern: Use existing service factory for Vertex AI creation
  • Strategy Pattern: Use for authentication method selection
  • Adapter Pattern: Adapt Vertex AI API to Cipher's interface
  • Observer Pattern: Use for event emission and monitoring

7.3 Error Handling Patterns

  • Implement exponential backoff for retryable errors
  • Use consistent error message formatting
  • Provide actionable error messages for configuration issues
  • Log detailed error context for debugging

7.4 Testing Patterns

  • Follow existing test structure and naming conventions
  • Use dependency injection for testability
  • Mock external dependencies (Vertex AI API)
  • Test both success and failure scenarios

8. Impacted Files / Modules Summary

New Files to Create:

  • src/core/brain/llm/services/vertex-ai.ts - Main Vertex AI service
  • src/core/brain/llm/services/vertex-ai-auth.ts - Authentication manager
  • src/core/brain/llm/services/__test__/vertex-ai.test.ts - Unit tests
  • src/core/brain/llm/services/__test__/vertex-ai.integration.test.ts - Integration tests

Files to Modify:

  • src/core/brain/llm/config.ts - Add Vertex AI config schema
  • src/core/brain/llm/services/factory.ts - Add Vertex AI case
  • src/core/brain/tools/unified-tool-manager.ts - Add Vertex AI tool formatting
  • src/core/env.ts - Add Vertex AI environment variables
  • package.json - Add Vertex AI dependencies

Files to Update:

  • README.md - Add Vertex AI setup documentation
  • examples/ - Add Vertex AI configuration examples
  • memAgent/cipher.yml - Add Vertex AI provider option

9. Definition of Done / Success Criteria

9.1 Functional Requirements

  • ✅ Vertex AI service implements full ILLMService interface
  • ✅ Tool calling works with all existing Cipher tools
  • ✅ Authentication supports both API key and service account
  • ✅ Regional endpoint configuration works correctly
  • ✅ Error handling and retry logic functions properly
  • ✅ Configuration validation prevents invalid setups

9.2 Performance Requirements

  • ✅ API call latency is comparable to other providers
  • ✅ Authentication token caching works efficiently
  • ✅ Tool execution performance meets existing standards
  • ✅ Memory usage is within acceptable limits

9.3 Quality Requirements

  • ✅ Unit test coverage exceeds 90%
  • ✅ Integration tests pass consistently
  • ✅ Error scenarios are properly handled
  • ✅ Logging provides sufficient debugging information
  • ✅ Documentation is complete and accurate

9.4 Usability Requirements

  • ✅ Configuration is straightforward and well-documented
  • ✅ Error messages are clear and actionable
  • ✅ Authentication setup is clearly explained
  • ✅ Examples demonstrate proper usage

9.5 Compatibility Requirements

  • ✅ Existing providers continue to work unchanged
  • ✅ Existing tools work with Vertex AI
  • ✅ Configuration format is consistent with other providers
  • ✅ API interface matches existing patterns

10. Open Questions / Future Considerations

10.1 Authentication Enhancements

  • Question: Should we support Application Default Credentials for enterprise deployments?
  • Consideration: This would simplify deployment in Google Cloud environments
  • Future: Implement ADC support as an optional authentication method

10.2 Advanced Features

  • Question: Should we support Vertex AI's advanced features like custom models?
  • Consideration: This would require additional configuration and API endpoints
  • Future: Add support for custom model endpoints and configurations

10.3 Performance Optimization

  • Question: Should we implement connection pooling for high-throughput scenarios?
  • Consideration: This would improve performance but add complexity
  • Future: Add connection pooling and request batching capabilities

10.4 Cost Management

  • Question: Should we add cost monitoring and quota management?
  • Consideration: This would help users manage Vertex AI costs
  • Future: Implement cost tracking and quota monitoring features

10.5 Regional Optimization

  • Question: Should we implement automatic region selection based on latency?
  • Consideration: This would improve performance but require additional logic
  • Future: Add automatic region selection and failover capabilities

billcache avatar Jul 18 '25 23:07 billcache