skatingP / PiscesAgent.py
sp103107's picture
Upload PiscesAgent.py
ed0d868 verified
Raw History Blame Contribute Delete
4.93 kB
import logging
import os
from dotenv import load_dotenv
import requests
from swarm import Swarm
# Load environment variables from .env file
load_dotenv()
# Configure logging
logging.basicConfig(level=logging.INFO, filename="pisces_agent.log", filemode="a",
format="%(asctime)s - %(levelname)s - %(message)s")
# --- Replace these with your actual agent calls ---
def get_nasa_data():
# Fetch planetary data from NASA API or service
logging.info("Fetching planetary data from NASA agent...")
# ... (your implementation using NASA_API_KEY) ...
return {'title': 'Jupiter and Saturn aligned'} # Replace with actual data
def get_moon_phase():
# Fetch moon phase data
logging.info("Fetching moon phase data...")
# ... (your implementation) ...
return {'moon_phase': 'New Moon'} # Replace with actual data
def get_tide_data():
# Fetch tide data from NOAA API
logging.info("Fetching tide data from NOAA API...")
# ... (your implementation using NOAA_API_KEY and NOAA_TIDE_API_URL) ...
return [{'v': 2.1}] # Replace with actual data
# --- End of agent calls ---
def generate_pisces_prediction():
"""Generate a Pisces horoscope using the Hugging Face Inference API."""
print("Starting prediction generation...")
try:
# Fetch data from other agents
planetary_data = get_nasa_data()
print("Planetary data:", planetary_data) # Debugging line
moon_phase_data = get_moon_phase()
print("Moon phase data:", moon_phase_data) # Debugging line
tide_data = get_tide_data()
print("Tide data:", tide_data) # Debugging line
# Extract relevant information
planetary_title = planetary_data.get('title', 'Unknown planetary influence')
moon_phase = moon_phase_data.get('moon_phase', 'Unknown phase')
tide_level = tide_data[0].get('v', 'N/A') if tide_data else "N/A"
prompt = (
f"Imagine you're a wise and whimsical astrologer, gazing at the stars. "
f"Tell me a captivating story about a Pisces person's day today, "
f"weaving in these celestial influences: the {moon_phase}, a {planetary_title}, "
f"and the ocean tides at {tide_level} meters. "
f"This story should be at least 300 words long and include: \n"
f"1. **A Vivid Description of the Pisces Person:** "
f"Describe their personality, current mood, and aspirations. \n"
f"2. **An Engaging Narrative of Their Day:** "
f"What challenges and opportunities do they encounter? "
f"Are there any significant interactions or decisions? \n"
f"3. **A Glimpse into Tomorrow:** "
f"What might the next day hold for them, considering the celestial influences? \n"
f"4. **Personalized Advice:** Offer insightful and inspiring guidance for "
f"their emotional, personal, and professional life. \n"
f"Remember to write in a captivating and imaginative style, "
f"evoking a sense of wonder and possibility."
)
# Use the Hugging Face Inference API with bigscience/T0_3B
api_url = "https://api-inference.huggingface.co/models/bigscience/T0_3B" # Updated URL
headers = {"Authorization": f"Bearer {os.getenv('HUGGINGFACE_API_KEY')}"}
response = requests.post(api_url, headers=headers, json={
"inputs": prompt,
"parameters": {
"max_new_tokens": 250, # Keep this within the API limit
"temperature": 0.8,
"do_sample": True,
"top_p": 0.9,
}
})
print("API response:", response.status_code, response.text) # For debugging
response.raise_for_status()
prediction = response.json()[0]['generated_text']
print("Prediction generated:", prediction)
# Save horoscope to a file
reports_dir = "reports"
os.makedirs(reports_dir, exist_ok=True)
filename = "pisces_horoscope.txt"
filepath = os.path.join(reports_dir, filename)
with open(filepath, "w") as file:
file.write("Pisces Horoscope Report\n")
file.write("========================\n")
file.write(prediction)
logging.info(f"Horoscope saved to {filepath}")
print(f"Prediction: {prediction}")
return {"prediction": prediction}
except Exception as e:
logging.error(f"Error generating prediction: {type(e).__name__}: {str(e)}")
return {"error": str(e)}
# Initialize the Swarm system with the Pisces agent function
swarm_system = Swarm(generate_pisces_prediction)
# Manually trigger the agent
if __name__ == "__main__":
generate_pisces_prediction() # Call the function directly
# (Optional) Start the Swarm system to handle other tasks/events
# swarm_system.run()