root 315326d0a2 feat(middleware): add auth, logging, and audit middleware
- Add authentication middleware with API key validation
- Add request logging middleware for observability
- Add audit logging middleware for admin operations
- Refactor API endpoints to use centralized auth middleware
- Add comprehensive unit tests for all middleware
- Add API documentation and deployment guide
- Update README with health endpoints and documentation links
- Fix test data isolation in router tests

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-03 03:23:37 +08:00

53 lines
1.7 KiB
Python

"""Anthropic Messages API endpoint."""
from typing import Annotated
from fastapi import APIRouter, Depends
from app.api.v1.chat import _calculate_cost, _log_request
from app.core.transformer import RequestTransformer
from app.db.database import get_db
from app.middleware.auth import AuthenticatedAPIKey
from app.schemas.anthropic import AnthropicMessagesRequest, AnthropicMessagesResponse
router = APIRouter(prefix="/v1", tags=["Messages"])
@router.post("/messages")
async def messages(
request: AnthropicMessagesRequest,
db: Annotated[None, Depends(get_db)],
api_key: AuthenticatedAPIKey,
) -> AnthropicMessagesResponse:
"""
Execute an Anthropic Messages API request.
This endpoint accepts Anthropic-format requests and forwards them
to the appropriate provider (Anthropic, OpenAI, etc.).
"""
from app.api.v1.chat import chat_completions
from app.schemas.openai import OpenAIChatCompletionRequest
# Convert Anthropic request to OpenAI format
transformer = RequestTransformer()
openai_request = transformer.anthropic_to_openai(request)
# Use the chat completions endpoint
from fastapi import HTTPException
from sqlalchemy.ext.asyncio import AsyncSession
# Re-import with correct type
from app.db.database import get_db as _get_db
from typing import AsyncGenerator
# Get database session
async for session in _get_db():
# Call chat completions with converted request
response = await chat_completions(openai_request, session, api_key)
# Convert response back to Anthropic format
anthropic_response = transformer.openai_response_to_anthropic(response)
return anthropic_response
raise HTTPException(status_code=500, detail="Database session error")