Spaces:
Sleeping
Sleeping
File size: 6,598 Bytes
a92d9d0 | 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 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 | # -*- coding: utf-8 -*-
"""utils.ipynb
Automatically generated by Colab.
Original file is located at
https://colab.research.google.com/drive/1mBC7DV-7zgoOK7ie6CXwhRvQyqsgJjiy
"""
# -*- coding: utf-8 -*-
"""utils.ipynb
Automatically generated by Colab.
Original file is located at
https://colab.research.google.com/drive/13uVA8g6FZq1KLvDxbVtgbp1trtKd_0W8
"""
import os
from langchain.chat_models import ChatOpenAI
from langchain.document_loaders import TextLoader
from langchain.embeddings import OpenAIEmbeddings
from langchain.vectorstores import FAISS
from langchain.chains.summarize import load_summarize_chain
from langchain.tools import Tool
from langchain.agents import initialize_agent, AgentType
from langchain.document_loaders import TextLoader
from langchain.text_splitter import CharacterTextSplitter, RecursiveCharacterTextSplitter
import geopy
import openai
from geopy.geocoders import Nominatim
import requests
import googlemaps
from langchain.schema import SystemMessage
# Using Google maps API
#gmaps = googlemaps.Client(key=os.getenv("GOOGLE_MAPS_API_KEY"))
gmaps = googlemaps.Client(key="AIzaSyDw18m127Esf_Phj-oaIcUN_2C3Ax2lXs4")
# Load API key from environment variable (Hugging Face Secrets)
#openai_api_key = os.getenv("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")
openai_api_key = "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" # your current key
# os.environ["OPENAI_API_KEY"] = openai_api_key
# Load and process docs
loader = TextLoader("./combined_text.txt")
documents = loader.load()
# Split text into chunks
text_splitter = RecursiveCharacterTextSplitter(chunk_size=1000, chunk_overlap=100)
docs = text_splitter.split_documents(documents)
embedding = OpenAIEmbeddings(openai_api_key=openai_api_key)
vectorstore = FAISS.from_documents(docs, embedding)
retriever = vectorstore.as_retriever()
system_message = SystemMessage(
content="""
You are a helpful mental health assistant. Always use the available tools to answer questions.
If the user asks about clinics or hospitals, call the clinic search tool and return its result directly (don't summarize).
Return full markdown responses (bold names, bullet points, maps, links).
"""
)
# llm = ChatOpenAI(model_name="gpt-4", temperature=0)
# summary_chain = load_summarize_chain(llm, chain_type="map_reduce")
llm = ChatOpenAI(model_name="gpt-3.5-turbo", openai_api_key=openai_api_key, temperature=0)
#llm = llm.bind_messages([system_message])
summary_chain = load_summarize_chain(llm, chain_type="map_reduce")
def suggest_helpline(query):
return """π Helplines:
- Crisis Text Line: Text HOME to 741741
- National Suicide Prevention Lifeline: 1-800-273-TALK
- Trevor Project (LGBTQ+): 1-866-488-7386"""
helpline_tool = Tool(
name="EmergencyHelpline",
func=suggest_helpline,
description="Offer emergency mental health helpline numbers based on distressing keywords."
)
def summarize_retrieved(query):
docs = retriever.get_relevant_documents(query)
return summary_chain.run(docs)
summarized_tool = Tool(
name="SummarizedDocSearch",
func=summarize_retrieved,
description="Use this tool to retrieve and summarize relevant information from symptoms, precausion, suggested food and activities from the knowledge base."
)
# def find_clinics(city, radius=10000):
# location = gmaps.geocode(city)[0]['geometry']['location']
# lat, lng = location['lat'], location['lng']
# places_result = gmaps.places_nearby(
# location=(lat, lng),
# radius=radius,
# keyword="mental health center",
# type="health"
# )
# results = places_result.get("results", [])[:5] # limit to 5 clinics
# details = []
# for place in results:
# place_id = place["place_id"]
# place_details = gmaps.place(place_id=place_id).get("result", {})
# name = place_details.get("name", "N/A")
# address = place_details.get("formatted_address", "N/A")
# phone = place_details.get("formatted_phone_number", "N/A")
# website = place_details.get("website", "N/A")
# rating = place_details.get("rating", "N/A")
# hours = place_details.get("opening_hours", {}).get("weekday_text", [])
# maps_link = f"https://maps.google.com/?cid={place_details.get('url', '').split('cid=')[-1]}" if "url" in place_details else "N/A"
# hours_md = "\n".join(hours) if hours else "No hours listed"
# website_md = f"[Website]({website})" if website != "N/A" else "N/A"
# details.append(f"""π₯ **{name}**
# π {address}
# π {phone}
# π {website_md}
# β Rating: {rating}
# π Working Hours:\n{hours_md}
# π [View on Google Maps]({maps_link})""")
# return "\n\n---\n\n".join(details) or "No clinics found."
def find_clinics(city, radius=10000):
location = gmaps.geocode(city)[0]['geometry']['location']
lat, lng = location['lat'], location['lng']
places_result = gmaps.places_nearby(
location=(lat, lng),
radius=radius,
keyword="mental health center",
type="health"
)
results = places_result.get("results", [])[:5]
clinics = []
for place in results:
place_id = place["place_id"]
details = gmaps.place(place_id=place_id).get("result", {})
clinics.append({
"name": details.get("name", "N/A"),
"address": details.get("formatted_address", "N/A"),
"phone": details.get("formatted_phone_number", "N/A"),
"lat": details.get("geometry", {}).get("location", {}).get("lat"),
"lng": details.get("geometry", {}).get("location", {}).get("lng"),
})
return clinics
clinic_finder_tool = Tool(
name="NearbyMentalHealthClinics",
func=lambda q: find_clinics(q),
description=(
"Use this tool when a user asks to find mental health clinics, hospitals, or centers "
"in a specific city or location. It returns detailed clinic info including: "
"name, full address, contact number, website, Google rating, opening hours, map link and suggested helpline numbers"
)
)
tools = [summarized_tool, helpline_tool, clinic_finder_tool]
agent = initialize_agent(
tools=tools,
llm=llm,
agent=AgentType.STRUCTURED_CHAT_ZERO_SHOT_REACT_DESCRIPTION,
verbose=True
) |