from fastapi import FastAPI, HTTPException from pydantic import BaseModel from typing import List, Dict, Optional import os from langchain_openai import ChatOpenAI from langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholder from langchain.schema import HumanMessage, SystemMessage from langchain.agents import AgentExecutor, create_openai_tools_agent from langchain.memory import ConversationBufferMemory from dotenv import load_dotenv import openai import stripe # Add stripe import # Project imports from src.tools import get_tools, get_supplements, get_prescription_drugs from src.payments.agent import process_purchase_request # Force reload environment variables from .env file load_dotenv(override=True) # Set OpenAI API key globally for all OpenAI services api_key = os.getenv("OPENAI_API_KEY") if not api_key: raise ValueError("OPENAI_API_KEY environment variable is not set") elif not api_key.startswith("sk-"): raise ValueError(f"Invalid API key format: {api_key[:10]}...") # Set Stripe API key stripe_key = os.getenv("STRIPE_API_KEY") if not stripe_key: raise ValueError("STRIPE_API_KEY environment variable is not set") stripe.api_key = stripe_key # Set for the OpenAI library directly openai.api_key = api_key os.environ["OPENAI_API_KEY"] = api_key # Ensure it's in environment variables # Print first few characters of API key for debugging (remove in production) print(f"Using API key starting with: {api_key[:10]}...") app = FastAPI() # Get data from tools module SUPPLEMENTS = get_supplements() PRESCRIPTION_DRUGS = get_prescription_drugs() class ChatMessage(BaseModel): session_id: str message: str class ChatResponse(BaseModel): response: str links: List[Dict[str, str]] = [] # Update the in-memory storage structure class ChatSession: def __init__(self, agent_executor: AgentExecutor, memory: ConversationBufferMemory, summary: str = ""): self.agent_executor = agent_executor self.memory = memory self.summary = summary # Update the storage dictionary chat_sessions = {} # Replace chat_histories and chat_summaries # Get all tools from the tools module tools = get_tools() @app.post("/chat", response_model=ChatResponse) async def handle_chat(chat_message: ChatMessage): session_id = chat_message.session_id # Initialize or retrieve chat session if session_id not in chat_sessions: # Create system prompt with empty summary system_message = """You are an expert longevity assistant specializing in evidence-based health optimization, supplementation, and prescription medications. ## YOUR ROLE: - Provide concise, scientifically-grounded advice on supplements, prescription medications, and longevity interventions - Focus on personalization based on the user's specific health concerns and goals - Maintain a friendly, supportive tone while being direct and efficient ## CONVERSATION FLOW: 1. Begin by asking clarifying questions about the user's specific health concerns 2. Once you understand their needs, recommend a focused set of solutions 3. For supplements or medications, use the get_product_details tool to provide information 4. If the user expresses interest in prescription products, recommend pre-paying for the product with a consultation 5. End with a brief encouraging remark related to their health goals ## PRESCRIPTION RECOMMENDATIONS: - When a user presents with a health concern, first ask clarifying questions - Based on their responses, recommend ONE or at most TWO prescription medications that would be most effective - Always clearly state that prescriptions require a medical consultation - Emphasize that prescription medications require a consultation with our nurse practitioner (additional fee applies) - Include this disclaimer with ANY prescription recommendation: "This medication requires a prescription from our nurse practitioner. Please schedule a consultation (additional fee applies)." ## COMPLEMENTARY APPROACHES: - When recommending a prescription medication, briefly mention 2-3 complementary supplements that may support the same health goal - Present these as educational information only, not as additional purchase suggestions - Use phrases like "Some people also find benefit from..." or "For a holistic approach, you might research..." - Do not include purchase links for these complementary supplements unless specifically requested ## PAYMENT HANDLING: - When a user expresses interest in purchasing prescription products, ask if they would like to pre-pay with a consultation - Generate ONE payment link for the entire purchase using the create_payment_link tool - Use the create_payment_link tool with a clear description of products and quantities (e.g., "I want to buy 1 tretinoin and 1 consultation") - After generating the payment link, ask for the user's email and phone number - Explain that payments will be refunded if the Nurse Practitioner determines the user doesn't meet the criteria - If a user requests additional products, ALWAYS check availability using get_available_products or check_product_availability before generating a payment link - If a user only wants to purchase a subset of recommended products, generate a payment link only for the products they want to purchase ## PRODUCT RESTRICTIONS: - ONLY recommend products available in our catalog - Use the get_available_products tool to check which products are available and use the exact names of the products in the catalog - DO NOT suggest products not in our catalog - Remember that NP_consultation is a valid product in our catalog - When a user asks to buy additional products, ALWAYS verify their availability before proceeding ## TOOLS AVAILABLE: - For supplements: search_supplements_by_condition, search_supplements_by_name, get_supplement_details, list_all_supplements - For prescription drugs: search_prescription_drugs_by_condition, search_prescription_drugs_by_name, get_prescription_drug_details, list_all_prescription_drugs - Combined searches: search_all_products_by_condition, search_all_products_by_name, get_product_details, list_all_products - Catalog verification: get_available_products - Payment: create_payment_link. This tool takes a string describing what products and quantities to purchase in a single transaction (e.g., "I want to buy 1 tretinoin and 1 consultation", "I want to buy 1 finasteride, 1 minoxidil and 1 consultation") ## GUIDELINES: - Keep responses under 150 words unless detailed information is requested - Use bullet points for clarity when listing multiple recommendations - Cite evidence categories (strong, moderate, preliminary) for recommendations - If a user asks for a product not in our catalog, politely explain we don't carry it and suggest available alternatives - If a user declines prescription options, gracefully recommend supplements or lifestyle changes instead ## TONE: - Professional but conversational - Evidence-based but accessible - Supportive without overpromising Remember to use the appropriate tool for each query type, and always prioritize user safety and scientific accuracy. """ # Create the prompt template prompt = ChatPromptTemplate.from_messages( [ ("system", system_message), MessagesPlaceholder(variable_name="chat_history", optional=True), ("human", "{input}"), MessagesPlaceholder(variable_name="agent_scratchpad"), ] ) # Initialize LLM and memory llm = ChatOpenAI(temperature=0.2, model="gpt-4o-mini", api_key=api_key) memory = ConversationBufferMemory(memory_key="chat_history", return_messages=True) # Create the agent agent = create_openai_tools_agent( llm=llm, tools=tools, prompt=prompt ) # Create the agent executor agent_executor = AgentExecutor( agent=agent, tools=tools, memory=memory, verbose=True ) # Store everything in the session chat_sessions[session_id] = ChatSession( agent_executor=agent_executor, memory=memory ) # Get the existing session session = chat_sessions[session_id] # Get response from agent result = await session.agent_executor.ainvoke({"input": chat_message.message}) response_text = result["output"] # Extract links from the response links = [] # Check for supplements first for supp_id, supp_data in SUPPLEMENTS.items(): if supp_id in response_text.lower() or supp_data["name"].lower() in response_text.lower(): links.append({ "name": supp_data["name"], "url": supp_data["affiliate_link"] }) # Check for prescription drugs for drug_id, drug_data in PRESCRIPTION_DRUGS.items(): if drug_id in response_text.lower() or drug_data["name"].lower() in response_text.lower(): links.append({ "name": drug_data["name"] + " (Prescription Required)", "url": drug_data["affiliate_link"] }) # Update the summary using the existing LLM summarizer_prompt = """Your role is to summarize the conversation, focusing on the user's medically relevant information, concerns, and any specific supplement or medication needs or preferences they express. Ensure the summary is concise and captures the essence of the user's health-related queries and the assistant's advice.""" # Get the last exchange last_exchange = f"User: {chat_message.message}\nAssistant: {response_text}" # Update the summary summarizer = ChatOpenAI(temperature=0.2, model="gpt-4o-mini", api_key=api_key) summary_update = summarizer.invoke([ SystemMessage(content=summarizer_prompt), HumanMessage(content=last_exchange) ]).content # Update the session summary session.summary = f"{session.summary} {summary_update}".strip() return ChatResponse( response=response_text, links=links ) @app.get("/welcome", response_model=dict) async def get_welcome_message(): """ Returns a welcome message for new users. """ return { "welcome_message": """ Welcome to the Longevity Assistant! 👋 I'm here to help you optimize your health and longevity journey. I can: • Answer questions about supplements and their benefits\n • Recommend products based on your specific health goals\n • Provide evidence-based information on longevity practices\n What health or longevity goal would you like to focus on today? """.strip(), "suggested_questions": [ "I am having hair loss issues", "I am having issues with my sleep", "I am finding it difficult to lose weight", "I am having memory issues", #"What supplements can help with cognitive function?", #"I'm looking for something to improve my sleep quality", #"What should I take for joint pain?", #"What's the best supplement for energy?", #"What's the best supplement for skin health?" ] }