Skip to content

feat: add 302AI provider integration #1235

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 3 commits into
base: main
Choose a base branch
from

Conversation

shiwo6324
Copy link

Description

Add 302AI Provider

Motivation

Expand the gateway's provider ecosystem

Type of Change

  • Bug fix (non-breaking change which fixes an issue)
  • New feature (non-breaking change which adds functionality)
  • Breaking change (fix or feature that would cause existing functionality to not work as expected)
  • Documentation update
  • Refactoring (no functional changes)

How Has This Been Tested?

  • Unit Tests
  • Integration Tests
  • Manual Testing

Screenshots (if applicable)

Checklist

  • My code follows the style guidelines of this project
  • I have performed a self-review of my own code
  • I have commented my code, particularly in hard-to-understand areas
  • I have made corresponding changes to the documentation
  • My changes generate no new warnings
  • I have added tests that prove my fix is effective or that my feature works
  • New and existing unit tests pass locally with my changes

Copy link

matter-code-review bot commented Jul 22, 2025

Code Quality new feature Performance Optimization Error Handling

Description

Summary By MatterAI MatterAI logo

🔄 What Changed

  • New Provider Integration: Added support for the 302AI provider, specifically integrating its /messages API endpoint, which includes extensive new types and transformation logic for Anthropic and Bedrock messages APIs.
  • Core Logic Refactoring: The central handlerUtils.ts file underwent a significant architectural overhaul, extracting core functionalities into dedicated, modular service classes: RequestContext, ProviderContext, CacheService, HooksService, LogsService, PreRequestValidatorService, and ResponseService. This streamlines request processing, error handling, caching, and logging.
  • Enhanced Logging: Standardized error logging across various handlers to use console.error with more comprehensive error objects. Introduced a new LogsService and LogObjectBuilder for structured, detailed request logging, improving observability.
  • Improved Caching Mechanism: The in-memory cache now supports maxAge (Time-To-Live) for cached responses, and caching logic is centralized within the new CacheService, allowing for more efficient resource management.
  • New API Endpoint: A new /v1/messages POST route was added to the Hono application, enabling communication with the new provider's messages API.
  • Dependency Update: Added portkey-ai as a new dependency in package.json to support the new integration.
  • Build Configuration Update: Modified rollup.config.js to exclude the tests directory from TypeScript compilation, optimizing the build process.

🔍 Impact of the Change

  • Increased Modularity & Maintainability: The refactoring into distinct service classes significantly improves the codebase's organization, making it easier to understand, maintain, and extend. Each service now has a clear, single responsibility.
  • Enhanced Observability: The new structured logging service provides richer, more consistent log data, which will greatly aid in debugging, monitoring, and tracing requests through the system, especially in complex distributed environments.
  • Improved Performance & Resource Management: The introduction of TTL for caching helps manage memory more effectively and can reduce redundant API calls for frequently accessed data, leading to better overall performance.
  • Expanded API Capabilities: The new /v1/messages endpoint allows the gateway to support a new class of AI models, specifically those following the Anthropic Messages API format, broadening the platform's utility and provider compatibility.
  • Robust Error Handling: Consistent error logging and improved retry mechanisms contribute to a more reliable and resilient system, reducing the impact of transient failures.
  • Comprehensive Test Coverage: The addition of extensive unit and integration tests for the new service layer and core functionalities drastically increases confidence in the stability and correctness of the changes, reducing the likelihood of regressions.

📁 Total Files Changed

  • .gitignore: Added src/handlers/tests/.creds.json to ignore list.
  • package.json: Added portkey-ai dependency.
  • rollup.config.js: Excluded tests directory from TypeScript compilation.
  • src/handlers/batchesHandler.ts: Updated error logging to console.error.
  • src/handlers/chatCompletionsHandler.ts: Updated error logging to console.error.
  • src/handlers/completionsHandler.ts: Updated error logging to console.error.
  • src/handlers/createSpeechHandler.ts: Updated error logging to console.error.
  • src/handlers/createTranscriptionHandler.ts: Updated error logging to console.error.
  • src/handlers/createTranslationHandler.ts: Updated error logging to console.error.
  • src/handlers/embeddingsHandler.ts: Updated error logging to console.error.
  • src/handlers/filesHandler.ts: Updated error logging to console.error.
  • src/handlers/finetuneHandler.ts: Updated error logging to console.error.
  • src/handlers/handlerUtils.ts: Major refactoring, removed old logic, integrated new service classes.
  • src/handlers/imageGenerationsHandler.ts: Updated error logging to console.error.
  • src/handlers/messagesHandler.ts: New file for /messages API handler.
  • src/handlers/modelResponsesHandler.ts: Updated error logging to console.error.
  • src/handlers/proxyHandler.ts: Updated error logging to console.error.
  • src/handlers/realtimeHandler.ts: Updated error logging to console.error.
  • src/handlers/responseHandlers.ts: Added messages endpoint to response transformer.
  • src/handlers/retryHandler.ts: Updated error logging for ConnectTimeoutError and generic errors.
  • src/handlers/services/cacheService.ts: New file for caching logic.
  • src/handlers/services/hooksService.ts: New file for hooks management.
  • src/handlers/services/logsService.ts: New file for structured logging.
  • src/handlers/services/preRequestValidatorService.ts: New file for pre-request validation.
  • src/handlers/services/providerContext.ts: New file for provider-specific context.
  • src/handlers/services/requestContext.ts: New file for request context management.
  • src/handlers/services/responseService.ts: New file for response handling.
  • src/handlers/websocketUtils.ts: Updated error logging to console.error.
  • src/index.ts: Added /v1/messages route and enhanced global error handler.
  • src/middlewares/cache/index.ts: Improved cache key generation and TTL support.
  • src/middlewares/hooks/types.ts: Added AllHookResults type.
  • src/middlewares/log/index.ts: Removed commented code.
  • src/providers/anthropic-base/constants.ts: New file for Anthropic stream constants.
  • src/providers/anthropic-base/messages.ts: New file for Anthropic messages config.
  • src/providers/anthropic-base/types.ts: New file for Anthropic base types.
  • src/providers/anthropic-base/utils/streamGenerator.ts: New file for Anthropic stream generation.
  • src/providers/anthropic/api.ts: Added messages endpoints.
  • src/providers/anthropic/chatComplete.ts: Refactored error response transform logic.
  • src/providers/anthropic/complete.ts: Refactored error response transform logic.
  • src/providers/anthropic/index.ts: Integrated new messages configurations.
  • src/providers/anthropic/messages.ts: New file for Anthropic messages handler.
  • src/providers/anthropic/types.ts: Added Anthropic error interfaces.
  • src/providers/anthropic/utils.ts: New file for Anthropic error response transform utility.
  • src/providers/azure-openai/utils.ts: Updated error logging to console.error.
  • src/providers/bedrock/api.ts: Added messages endpoints.
  • src/providers/bedrock/chatComplete.ts: Refactored types and error response transform logic.
  • src/providers/bedrock/index.ts: Integrated new messages configurations.
  • src/providers/bedrock/messages.ts: New file for Bedrock Converse messages API.
  • src/providers/bedrock/types.ts: Added Bedrock messages related types.
  • src/providers/bedrock/utils.ts: Updated error logging to console.error.
  • src/providers/bedrock/utils/messagesUtils.ts: New file for Bedrock messages utility functions.
  • src/providers/google-vertex-ai/api.ts: Added messages endpoints.
  • src/providers/google-vertex-ai/chatComplete.ts: Updated imports.
  • src/providers/google-vertex-ai/index.ts: Integrated new messages configurations.
  • src/providers/google-vertex-ai/messages.ts: New file for Vertex AI Anthropic messages handler.
  • src/providers/types.ts: Updated endpointStrings type to include new message endpoints.
  • src/providers/utils.ts: Added transformToAnthropicStopReason function and updated imports.
  • src/providers/utils/finishReasonMap.ts: Added AnthropicFinishReasonMap.
  • src/types/MessagesRequest.ts: New file defining Anthropic Messages API request types.
  • src/types/MessagesStreamResponse.ts: New file defining Anthropic Messages API stream response types.
  • src/types/messagesResponse.ts: New file defining Anthropic Messages API response types.
  • src/types/requestBody.ts: Exported RetrySettings and CacheSettings, added description to ToolCall.
  • tests/integration/src/handlers/requestBuilder.ts: New file for integration test request building utilities.
  • tests/integration/src/handlers/test.txt: New file for test data.
  • tests/integration/src/handlers/tryPost.test.ts: New file with extensive integration tests covering core functionality, error handling, hooks, and caching.
  • tests/unit/src/handlers/services/benchmark.ts: New file for logging service benchmarks.
  • tests/unit/src/handlers/services/cacheService.test.ts: New file with unit tests for CacheService.
  • tests/unit/src/handlers/services/hooksService.test.ts: New file with unit tests for HooksService.
  • tests/unit/src/handlers/services/logsService.test.ts: New file with unit tests for LogsService and LogObjectBuilder.
  • tests/unit/src/handlers/services/preRequestValidatorService.test.ts: New file with unit tests for PreRequestValidatorService.
  • tests/unit/src/handlers/services/providerContext.test.ts: New file with unit tests for ProviderContext.
  • tests/unit/src/handlers/services/requestContext.test.ts: New file with unit tests for RequestContext.
  • tests/unit/src/handlers/services/responseService.test.ts: New file with unit tests for ResponseService.

🧪 Test Added

  • tests/integration/src/handlers/tryPost.test.ts: This new file introduces comprehensive integration tests for the tryPost function, which is the core of the gateway's request handling. It covers: basic synchronous and streaming chat completions, binary file uploads using FormData, audio transcription with ArrayBuffer, image generation, and proxy requests to various endpoints. It also includes tests for handling invalid providers, verifying retry logic for specific status codes, and confirming request timeouts. Crucially, it features extensive tests for before_request_hooks (including allowing, blocking, and transforming requests) and after_request_hooks (executing on responses, handling failures with retries, and async behavior). Caching functionality is also validated, including simple cache mode, non-cacheable endpoints, and cache TTL. Skipped tests for specific providers (Azure OpenAI, AWS Bedrock, Google Vertex AI) are noted for future implementation.
  • Unit Tests for New Services (tests/unit/src/handlers/services/*.test.ts): A suite of new unit test files has been added to thoroughly test the newly introduced service layer. cacheService.test.ts verifies cacheability, retrieval, and integration with hooks. hooksService.test.ts tests hook span creation, result retrieval, and sync hook availability. logsService.test.ts and benchmark.ts validate structured log object creation, management, and performance. preRequestValidatorService.test.ts ensures correct execution and response handling for pre-request validators. providerContext.test.ts confirms proper retrieval of provider-specific configurations and handlers. requestContext.test.ts validates request data initialization, normalization, and transformation. Finally, responseService.test.ts tests response creation, header manipulation, and integration with the response handler.

🔒Security Vulnerabilities

  • N/A: No new security vulnerabilities were introduced in this pull request. The addition of src/handlers/tests/.creds.json to the .gitignore file is a positive security practice, preventing sensitive test credentials from being inadvertently committed to the repository. The architectural refactoring into distinct service classes inherently improves the overall security posture by promoting cleaner code, better separation of concerns, and clearer data flows, which can reduce the attack surface and make potential vulnerabilities easier to identify and mitigate in the future.

Motivation

This PR introduces a new AI provider integration (302AI) and significantly refactors the core request handling logic into a service-oriented architecture. This refactoring improves modularity, maintainability, testability, and observability of the gateway, making it more robust and easier to extend with future features and providers. The new structured logging and caching mechanisms enhance performance and debugging capabilities.

Type of Change

  • New feature (non-breaking change which adds functionality)
  • Bug fix (non-breaking change which fixes an issue)
  • Breaking change (fix or feature that would cause existing functionality to not work as expected)
  • Documentation update
  • Refactoring (no functional changes)

How Has This Been Tested?

  • Unit Tests
  • Integration Tests
  • Manual Testing

Screenshots (if applicable)

N/A

Checklist

  • My code follows the style guidelines of this project
  • I have performed a self-review of my own code
  • I have commented my code, particularly in hard-to-understand areas
  • I have made corresponding changes to the documentation
  • My changes generate no new warnings
  • I have added tests that prove my fix is effective or that my feature works
  • New and existing unit tests pass locally with my changes

Related Issues

N/A

Tip

Quality Recommendations

  1. Ensure all console.error calls consistently log the full error object (e.g., console.error('handlerName error:', err);) to capture stack traces and full error details, rather than just err.message.

  2. For production environments, consider replacing the in-memory inMemoryCache in src/middlewares/cache/index.ts with a distributed caching solution (e.g., Redis, Cloudflare KV) to ensure cache consistency and scalability across multiple worker instances.

  3. Remove commented-out code, such as the isComplete method in LogObjectBuilder and the content-encoding/transfer-encoding header removal logic in ResponseService.updateHeaders, to improve readability and reduce technical debt.

  4. Prioritize enabling and implementing the skipped integration tests for Azure OpenAI, AWS Bedrock, and Google Vertex AI to ensure full coverage for provider-specific functionalities.

Copy link

@matter-code-review matter-code-review bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This PR adds integration for the 302AI provider with chat completion functionality. The implementation follows the existing patterns for provider integration, but I have a few suggestions to improve the code.

Comment on lines +150 to +153
} catch (error) {
console.error('Error parsing 302AI stream chunk:', error);
return `data: ${chunk}\n\n`;
}

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Code Refactor

Issue: The error handling in the stream chunk transformation could be improved to provide more specific error information.
Fix: Add more context to the error logging to help with debugging.
Impact: Improves troubleshooting capabilities when stream parsing fails.

Suggested change
} catch (error) {
console.error('Error parsing 302AI stream chunk:', error);
return `data: ${chunk}\n\n`;
}
} catch (error) {
console.error('Error parsing 302AI stream chunk:', error, 'Chunk:', chunk);
return `data: ${chunk}\
\
`;
}

Comment on lines +8 to +15
getEndpoint: ({ fn }) => {
switch (fn) {
case 'chatComplete':
return '/v1/chat/completions';
default:
return '';
}
},

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Code Refactor

Issue: The API endpoint handling doesn't include a case for potential future endpoints.
Fix: Add a more descriptive error for unsupported function types.
Impact: Improves developer experience when implementing new functions.

Suggested change
getEndpoint: ({ fn }) => {
switch (fn) {
case 'chatComplete':
return '/v1/chat/completions';
default:
return '';
}
},
getEndpoint: ({ fn }) => {
switch (fn) {
case 'chatComplete':
return '/v1/chat/completions';
default:
console.warn(`Unsupported function type for 302AI: ${fn}`);
return '';
}
},

Comment on lines +122 to +126
) => string = (responseChunk) => {
let chunk = responseChunk.trim();
chunk = chunk.replace(/^data: /, '');
chunk = chunk.trim();

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚡️ Performance Improvement

Issue: The stream chunk parsing has redundant trim operations.
Fix: Combine the trim operations into a single step.
Impact: Slightly improves performance by reducing string operations.

Suggested change
) => string = (responseChunk) => {
let chunk = responseChunk.trim();
chunk = chunk.replace(/^data: /, '');
chunk = chunk.trim();
) => {
let chunk = responseChunk.replace(/^data: /, '').trim();
if (chunk === '[DONE]') {

@shiwo6324 shiwo6324 changed the title Feat/302 ai integration feat: add 302AI provider integration Jul 22, 2025
Copy link

Important

PR Review Skipped

PR review skipped as per the configuration setting. Run a manually review by commenting /matter review

💡Tips to use Matter AI

Command List

  • /matter summary: Generate AI Summary for the PR
  • /matter review: Generate AI Reviews for the latest commit in the PR
  • /matter review-full: Generate AI Reviews for the complete PR
  • /matter release-notes: Generate AI release-notes for the PR
  • /matter : Chat with your PR with Matter AI Agent
  • /matter remember : Generate AI memories for the PR
  • /matter explain: Get an explanation of the PR
  • /matter help: Show the list of available commands and documentation
  • Need help? Join our Discord server: https://discord.gg/fJU5DvanU3

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant