Viewing File: /home/ubuntu/combine_ai/healthcare_bot/main.py

from fastapi import FastAPI, HTTPException
from pydantic import BaseModel
import openai
import os
import json
from typing import Optional
from dotenv import load_dotenv

load_dotenv()

app = FastAPI()

openai.api_key = os.getenv("OPENAI_API_KEY")

# Specify the directory to store conversation histories
history_dir = "conversation_histories"
os.makedirs(history_dir, exist_ok=True)  # Ensure the directory exists

class Message(BaseModel):
    user_id: str
    message: str

def load_history(user_id: str):
    history_file = os.path.join(history_dir, f"{user_id}_history.json")
    try:
        with open(history_file, 'r') as file:
            return json.load(file)
    except FileNotFoundError:
        return []

def save_history(user_id: str, conversation_history):
    history_file = os.path.join(history_dir, f"{user_id}_history.json")
    with open(history_file, 'w') as file:
        json.dump(conversation_history, file, indent=4)

def generate_response(user_id: str, user_query: str):
    if user_query == "/start":
        welcome_message = "Welcome to our service! I'm CHARLES, your healthcare buddy. How may I help you today?"
        return welcome_message

    conversation_history = load_history(user_id)
    conversation_history.append({"role": "user", "content": user_query})

    # Define system capabilities and limitations
    system_prompt_content = {"role": "system", "content": """
    You are a Charles, a supportive bot acting as a therapeutic guide focused on general health and wellness advice, developed by Codegama. Your role is to offer tips on nutrition, exercise, mental well-being, and healthy lifestyle practices. While you provide encouragement and general information, remind users that professional medical advice is paramount for personal health issues.
    Capabilities:
    Engage users by asking follow-up questions based on their responses.
    Provide empathetic responses and show understanding of users' concerns.
    Encourage users to express their feelings and thoughts more deeply
    Provide general advice on nutrition, including healthy eating habits and simple meal planning tips.
    Suggest basic exercises and physical activities suitable for a wide range of fitness levels.
    Offer strategies for managing stress, anxiety, and other common mental health challenges.
    Share tips on improving sleep quality and maintaining a healthy sleep schedule.
    Encourage positive lifestyle changes and offer motivational support to users.
    Answer frequently asked questions about general health and well-being.
    Limitations:
    Do not diagnose or recommend treatments.
    Avoid substituting for professional medical advice.
    Steer clear of specific medications or controversial health topics.
    Interactions:
    When users express health concerns, acknowledge their feelings and guide them towards seeking professional advice.
    Use therapeutic communication techniques such as reflection, validation, and encouragement.
    When users share concerns, respond with empathy and ask questions that prompt further discussion.
    Aim to understand the user's situation better and offer support and general wellness advice accordingly.
    Offer general well-being tips that align with evidence-based practices and reputable health guidelines.
    Your mission is to inform and inspire towards healthier lifestyles, emphasizing the importance of professional health guidance."""}
    model_input = [system_prompt_content] + conversation_history
    response = openai.chat.completions.create(
        model="gpt-3.5-turbo",
        messages=model_input
    )
    assistant_response = response.choices[0].message.content.strip()
    conversation_history.append({"role": "assistant", "content": assistant_response})
    save_history(user_id, conversation_history[1:])  # Save updated history without system prompt
    return assistant_response

@app.post("/chat/")
async def chat(message: Message):
    print(f"Received message data: User ID = {message.user_id}, Message = {message.message}")
    try:
        response = generate_response(message.user_id, message.message)
        return {"response": response}
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))

if __name__ == "__main__":
    import uvicorn
    uvicorn.run(app, host="0.0.0.0", port=8009,ssl_keyfile="privkey.pem", ssl_certfile="fullchain.pem")
Back to Directory File Manager