|
| 1 | +import logging |
| 2 | +from typing import Any |
| 3 | + |
| 4 | +try: |
| 5 | + from fastapi import APIRouter, HTTPException |
| 6 | + from fastapi.responses import StreamingResponse |
| 7 | + from openai.types import ErrorObject |
| 8 | + from openai.types.chat.chat_completion import ChatCompletion |
| 9 | + from openai.types.model import Model |
| 10 | + from openai.types.responses import Response |
| 11 | +except ImportError as _import_error: # pragma: no cover |
| 12 | + raise ImportError( |
| 13 | + 'Please install the `openai` package to enable the fastapi openai compatible endpoint, ' |
| 14 | + 'you can use the `openai` and `fastapi` optional group — `pip install "pydantic-ai-slim[openai,fastapi]"`' |
| 15 | + ) from _import_error |
| 16 | + |
| 17 | +from pydantic_ai.fastapi.api import AgentChatCompletionsAPI, AgentModelsAPI, AgentResponsesAPI |
| 18 | +from pydantic_ai.fastapi.data_models import ( |
| 19 | + ChatCompletionRequest, |
| 20 | + ErrorResponse, |
| 21 | + ModelsResponse, |
| 22 | + ResponsesRequest, |
| 23 | +) |
| 24 | +from pydantic_ai.fastapi.registry import AgentRegistry |
| 25 | + |
| 26 | +logger = logging.getLogger(__name__) |
| 27 | + |
| 28 | + |
| 29 | +class AgentAPIRouter(APIRouter): |
| 30 | + """FastAPI Router for Pydantic Agent.""" |
| 31 | + |
| 32 | + def __init__( |
| 33 | + self, |
| 34 | + agent_registry: AgentRegistry, |
| 35 | + disable_response_api: bool = False, |
| 36 | + disable_completions_api: bool = False, |
| 37 | + *args: tuple[Any], |
| 38 | + **kwargs: tuple[Any], |
| 39 | + ): |
| 40 | + super().__init__(*args, **kwargs) |
| 41 | + self.registry = agent_registry |
| 42 | + self.responses_api = AgentResponsesAPI(self.registry) |
| 43 | + self.completions_api = AgentChatCompletionsAPI(self.registry) |
| 44 | + self.models_api = AgentModelsAPI(self.registry) |
| 45 | + self.enable_responses_api = not disable_response_api |
| 46 | + self.enable_completions_api = not disable_completions_api |
| 47 | + |
| 48 | + # Registers OpenAI/v1 API routes |
| 49 | + self._register_routes() |
| 50 | + |
| 51 | + def _register_routes(self) -> None: # noqa: C901 |
| 52 | + if self.enable_completions_api: |
| 53 | + |
| 54 | + @self.post( |
| 55 | + '/v1/chat/completions', |
| 56 | + response_model=ChatCompletion, |
| 57 | + ) |
| 58 | + async def chat_completions( # type: ignore |
| 59 | + request: ChatCompletionRequest, |
| 60 | + ) -> ChatCompletion | StreamingResponse: |
| 61 | + if not request.messages: |
| 62 | + raise HTTPException( |
| 63 | + status_code=400, |
| 64 | + detail=ErrorResponse( |
| 65 | + error=ErrorObject( |
| 66 | + type='invalid_request_error', |
| 67 | + message='Messages cannot be empty', |
| 68 | + ), |
| 69 | + ).model_dump(), |
| 70 | + ) |
| 71 | + try: |
| 72 | + if getattr(request, 'stream', False): |
| 73 | + return StreamingResponse( |
| 74 | + self.completions_api.create_streaming_completion(request), |
| 75 | + media_type='text/event-stream', |
| 76 | + headers={ |
| 77 | + 'Cache-Control': 'no-cache', |
| 78 | + 'Connection': 'keep-alive', |
| 79 | + 'Content-Type': 'text/plain; charset=utf-8', |
| 80 | + }, |
| 81 | + ) |
| 82 | + else: |
| 83 | + return await self.completions_api.create_completion(request) |
| 84 | + except Exception as e: |
| 85 | + logger.error(f'Error in chat completion: {e}', exc_info=True) |
| 86 | + raise HTTPException( |
| 87 | + status_code=500, |
| 88 | + detail=ErrorResponse( |
| 89 | + error=ErrorObject( |
| 90 | + type='internal_server_error', |
| 91 | + message=str(e), |
| 92 | + ), |
| 93 | + ).model_dump(), |
| 94 | + ) |
| 95 | + |
| 96 | + if self.enable_responses_api: |
| 97 | + |
| 98 | + @self.post( |
| 99 | + '/v1/responses', |
| 100 | + response_model=Response, |
| 101 | + ) |
| 102 | + async def responses( # type: ignore |
| 103 | + request: ResponsesRequest, |
| 104 | + ) -> Response: |
| 105 | + if not request.input: |
| 106 | + raise HTTPException( |
| 107 | + status_code=400, |
| 108 | + detail=ErrorResponse( |
| 109 | + error=ErrorObject( |
| 110 | + type='invalid_request_error', |
| 111 | + message='Messages cannot be empty', |
| 112 | + ), |
| 113 | + ).model_dump(), |
| 114 | + ) |
| 115 | + try: |
| 116 | + if getattr(request, 'stream', False): |
| 117 | + # TODO: add streaming support for responses api |
| 118 | + raise HTTPException(status_code=501) |
| 119 | + else: |
| 120 | + return await self.responses_api.create_response(request) |
| 121 | + except Exception as e: |
| 122 | + logger.error(f'Error in responses: {e}', exc_info=True) |
| 123 | + raise HTTPException( |
| 124 | + status_code=500, |
| 125 | + detail=ErrorResponse( |
| 126 | + error=ErrorObject( |
| 127 | + type='internal_server_error', |
| 128 | + message=str(e), |
| 129 | + ), |
| 130 | + ).model_dump(), |
| 131 | + ) |
| 132 | + |
| 133 | + @self.get('/v1/models', response_model=ModelsResponse) |
| 134 | + async def get_models() -> ModelsResponse: # type: ignore |
| 135 | + try: |
| 136 | + return await self.models_api.list_models() |
| 137 | + except Exception as e: |
| 138 | + logger.error(f'Error listing models: {e}', exc_info=True) |
| 139 | + raise HTTPException( |
| 140 | + status_code=500, |
| 141 | + detail=ErrorResponse( |
| 142 | + error=ErrorObject( |
| 143 | + type='internal_server_error', |
| 144 | + message=f'Error retrieving models: {str(e)}', |
| 145 | + ), |
| 146 | + ).model_dump(), |
| 147 | + ) |
| 148 | + |
| 149 | + @self.get('/v1/models' + '/{model_id}', response_model=Model) |
| 150 | + async def get_model(model_id: str) -> Model: # type: ignore |
| 151 | + try: |
| 152 | + return await self.models_api.get_model(model_id) |
| 153 | + except HTTPException: |
| 154 | + raise |
| 155 | + except Exception as e: |
| 156 | + logger.error(f'Error fetching model info: {e}', exc_info=True) |
| 157 | + raise HTTPException( |
| 158 | + status_code=500, |
| 159 | + detail=ErrorResponse( |
| 160 | + error=ErrorObject( |
| 161 | + type='internal_server_error', |
| 162 | + message=f'Error retrieving model: {str(e)}', |
| 163 | + ), |
| 164 | + ).model_dump(), |
| 165 | + ) |
0 commit comments