from typing import Any from fastapi import HTTPException, status from app.modules.ai_agent.constants import ( CHAT_USER_CONTENT_TEMPLATE, COMPANY_MANAGEMENT_SYSTEM_INSTRUCTIONS, UNEXPECTED_HERMES_RESPONSE, AIChatRole, AIErrorKey, AIHttpPayloadKey, AIResponseKey, ) def _error_detail(exc: Exception) -> Any: if isinstance(exc, HTTPException): return exc.detail return {AIResponseKey.TYPE: type(exc).__name__, AIResponseKey.MESSAGE: str(exc)} def _response_payload(response: Any) -> dict[str, Any]: try: data = response.json() except ValueError: data = {AIResponseKey.TEXT: response.text} return {AIResponseKey.STATUS_CODE: response.status_code, AIResponseKey.DATA: data} def _chat_completion_payload(response: Any, error_key: AIErrorKey) -> dict[str, Any]: try: return response.json() except ValueError as exc: raise HTTPException( status_code=status.HTTP_502_BAD_GATEWAY, detail={ error_key: UNEXPECTED_HERMES_RESPONSE, AIResponseKey.RAW: {AIResponseKey.TEXT: response.text}, }, ) from exc def _chat_messages(prompt: str, context: dict[str, Any] | None = None) -> list[dict[str, str]]: return [ { AIHttpPayloadKey.ROLE: AIChatRole.SYSTEM, AIHttpPayloadKey.CONTENT: COMPANY_MANAGEMENT_SYSTEM_INSTRUCTIONS, }, { AIHttpPayloadKey.ROLE: AIChatRole.USER, AIHttpPayloadKey.CONTENT: CHAT_USER_CONTENT_TEMPLATE.format( context=context or {}, task=prompt, ), }, ] def _service_root(base_url: str, suffix: str) -> str: root = base_url.rstrip("/") normalized_suffix = suffix.rstrip("/") if root.endswith(normalized_suffix): root = root[: -len(normalized_suffix)] return root.rstrip("/")