Spaces:
Runtime error
Runtime error
File size: 2,717 Bytes
28baf2e | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 | import logging
import json
from typing import List, Dict, Any
from langchain_core.documents import Document
from insucompass.services import llm_provider
from insucompass.config import settings
from insucompass.prompts.prompt_loader import load_prompt
# Configure logging
logging.basicConfig(level=settings.LOG_LEVEL, format='%(asctime)s - %(levelname)s - %(message)s')
logger = logging.getLogger(__name__)
llm = llm_provider.get_gemini_llm()
class PlanAgent:
"""
An agent that analyzes a user profile and retrieved documents to
recommend the top 3 most suitable health insurance plans.
"""
def __init__(self):
"""Initializes the PlanAgent."""
try:
self.agent_prompt = load_prompt("plan_agent")
logger.info("PlanAgent initialized successfully.")
except FileNotFoundError:
logger.critical("PlanAgent prompt file not found. The agent cannot function.")
raise
def generate_recommendations(
self,
user_profile: Dict[str, Any],
documents: List[Document]
) -> Dict[str, Any]:
"""
Generates plan recommendations in a structured JSON format.
"""
if not documents:
logger.warning("PlanAgent received no documents. Cannot generate recommendations.")
return {"recommendations": []}
profile_str = json.dumps(user_profile, indent=2)
context_str = "\n\n---\n\n".join([d.page_content for d in documents])
full_prompt = (
f"{self.agent_prompt}\n\n"
f"### CONTEXT FOR YOUR RECOMMENDATION\n"
f"user_profile: {profile_str}\n\n"
f"retrieved_context:\n{context_str}"
)
logger.info("Generating plan recommendations with PlanAgent...")
try:
response = llm.invoke(full_prompt)
# Clean the response to ensure it's valid JSON
response_content = response.content.strip().replace("```json", "").replace("```", "")
recommendations = json.loads(response_content)
logger.info(f"Successfully generated structured plan recommendations \n\n {recommendations}.")
return recommendations
except json.JSONDecodeError as e:
logger.error(f"Failed to decode JSON from PlanAgent: {e}\nResponse was: {response.content}")
return {"recommendations": [], "error": "Failed to generate plan recommendations."}
except Exception as e:
logger.error(f"Error during plan recommendation generation: {e}")
return {"recommendations": [], "error": "An error occurred while generating plans."}
# Singleton instance
planner = PlanAgent() |