Spaces:
Sleeping
Sleeping
| # Commented out IPython magic to ensure Python compatibility. | |
| # %pip install llama-index-llms-google-genai llama-index | |
| # %pip install requests | |
| # %pip install gradio | |
| import os | |
| import requests | |
| import gradio as gr | |
| from llama_index.llms.gemini import Gemini | |
| from llama_index.core.llms import ChatMessage | |
| OPENWEATHER_API_KEY = os.getenv("OPENWEATHER_API_KEY") | |
| GEMINI_KEY = os.getenv("GEMINI_KEY") | |
| if not OPENWEATHER_API_KEY or not GEMINI_KEY: | |
| raise RuntimeError("Chaves de API não configuradas. Defina as secrets no Hugging Face Spaces.") | |
| # Inicia a llm | |
| llm = Gemini( | |
| model="models/gemini-2.5-flash", | |
| api_key=GEMINI_KEY | |
| ) | |
| # Buscar clima | |
| def buscar_clima(cidade: str, lang="pt") -> str: | |
| try: | |
| url = f"http://api.openweathermap.org/data/2.5/weather?q={cidade}&appid={OPENWEATHER_API_KEY}&units=metric&lang={lang}" | |
| resposta = requests.get(url) | |
| data = resposta.json() | |
| if data.get("cod") != 200: | |
| return f"Não consegui encontrar o clima para {cidade}." | |
| # Obter dados do clima | |
| desc = data["weather"][0]["description"] | |
| temp = data["main"]["temp"] | |
| feels = data["main"]["feels_like"] | |
| pais = data["sys"]["country"] | |
| # obter latitude e longitude | |
| lat = data["coord"]["lat"] | |
| lon = data["coord"]["lon"] | |
| # Chamada reversa para obter o estado | |
| geo_url = f"http://api.openweathermap.org/geo/1.0/reverse?lat={lat}&lon={lon}&limit=1&appid={OPENWEATHER_API_KEY}" | |
| geo_data = requests.get(geo_url).json() | |
| estado = geo_data[0].get("state", "Desconhecido") | |
| # Retorna estas informações para a llm interpretar | |
| return ( | |
| f"O clima em {cidade} ({estado}, {pais}) é {desc}, " | |
| f"com temperatura de {temp}°C (sensação térmica de {feels}°C)." | |
| ) | |
| except Exception as e: | |
| return f"Erro ao obter o clima: {e}" | |
| # Função que cria o comportamento do bot | |
| def chat_bot(user_input, historico): | |
| cidade = user_input.strip() | |
| clima = buscar_clima(cidade) | |
| # Prompt de instrução de comportamento para o bot | |
| mensagens = [ | |
| ChatMessage( | |
| role="system", | |
| content= f"O usuário pediu o clima no seu estado na resposta: {user_input}. " | |
| f"A informação do clima é: {clima}. Responda de forma natural e educada, " | |
| f"citando todas as informações obtidas do clima. Após isso recomende ao " | |
| f"usuário um passeio em uma das mais importantes cidades deste estado, " | |
| f"baseando-se nas informações obtidas do clima.") | |
| ] | |
| resposta = llm.chat(mensagens) | |
| resposta_bot = resposta.message.content | |
| return resposta_bot | |
| def criar_interface(): | |
| chat = gr.ChatInterface( | |
| fn=chat_bot, | |
| title="Clima Tour Bot🌤️", | |
| description="Envie ao bot o nome do Estado que você deseja saber sobre o clima e possíveis recomendações!", | |
| theme="soft" | |
| ) | |
| chat.launch(debug=True) | |
| if __name__ == "__main__": | |
| criar_interface() |