Spaces:
Sleeping
Sleeping
Download utils.py from Jaamie/SafeSpace_Agent: direct link, hf CLI and curl.
- Browser
- Download file 6.6 kB
-
https://huggingface.co/spaces/Jaamie/SafeSpace_Agent/resolve/main/utils.py
- Command line
-
hf download hf://spaces/Jaamie/SafeSpace_Agent/utils.py
-
curl -L -o utils.py https://huggingface.co/spaces/Jaamie/SafeSpace_Agent/resolve/main/utils.py
6.6 kB
| # -*- 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 | |
| ) |