Spaces:
Runtime error
Runtime error
| from autogen_agentchat.agents import AssistantAgent | |
| from autogen_ext.models.openai import OpenAIChatCompletionClient | |
| from autogen_ext.code_executors.local import LocalCommandLineCodeExecutor | |
| from autogen_ext.tools.code_execution import PythonCodeExecutionTool | |
| import os | |
| from autogen_agentchat.teams import RoundRobinGroupChat | |
| from autogen_core import CancellationToken | |
| from datetime import datetime | |
| from geopy.geocoders import Nominatim | |
| import requests | |
| from datetime import timedelta | |
| import asyncio | |
| geolocator = Nominatim(user_agent="JuraganAI") | |
| # Initialize model client | |
| model_client = OpenAIChatCompletionClient( | |
| model="gemini-2.0-flash", | |
| api_key=os.getenv("google_api_key"), | |
| base_url="https://generativelanguage.googleapis.com/v1beta/openai/" | |
| ) | |
| # Define weather tool | |
| def get_weather_forecast(location: str, number_of_days: int = 0): | |
| """Retrieves the weather using Open-Meteo API for a given location (city) and number of days from current.""" | |
| now = datetime.now() | |
| date = now + timedelta(days=number_of_days) | |
| date = date.strftime("%Y-%m-%d") | |
| try: | |
| location_obj = geolocator.geocode(location) | |
| if location_obj: | |
| response = requests.get( | |
| f"https://api.open-meteo.com/v1/forecast?" | |
| f"latitude={location_obj.latitude}&longitude={location_obj.longitude}" | |
| f"&start_date={date}&end_date={date}&daily=temperature_2m_max,temperature_2m_min,precipitation_sum" | |
| ) | |
| data = response.json() | |
| return data | |
| else: | |
| return {"error": "Location not found"} | |
| except Exception as e: | |
| return {"error": str(e)} | |
| os.makedirs("coding", exist_ok=True) | |
| coding_tool = PythonCodeExecutionTool(LocalCommandLineCodeExecutor(work_dir="coding")) | |
| # Create assistant agent with weather tool (no code execution here) | |
| assistant = AssistantAgent( | |
| "smart_assistant", | |
| model_client=model_client, | |
| tools=[get_weather_forecast, coding_tool], | |
| system_message=""" | |
| Nama kamu Juan, kamu adalah Voice Agent dari Juragan AI, asisten yang suka menolong dengan kepribadian yang hangat. | |
| Kamu adalah asisten AI serba guna yang dapat menangani semua jenis pertanyaan atau tugas. | |
| Kamu memiliki kemampuan berikut: | |
| 1. **Pengetahuan Umum**: Menjawab pertanyaan tentang topik apa pun - sains, sejarah, teknologi, dll. | |
| 2. **Informasi Cuaca**: Menggunakan alat get_weather_forecast saat pengguna bertanya tentang cuaca untuk lokasi tertentu | |
| 3. **Kode & Analisis**: Menulis kode Python untuk perhitungan, analisis data, dan visualisasi | |
| 4. **Pemecahan Masalah**: Membantu dengan matematika, masalah logika, penjelasan, dan solusi langkah demi langkah | |
| **Pedoman Pengambilan Keputusan:** | |
| - Jika pengguna bertanya tentang cuaca untuk lokasi tertentu, gunakan alat get_weather_forecast. Jika hari ini maka number_of_days adalah 0, besok adalah 1, dan seterusnya. | |
| - Jika pengguna memerlukan kalkulasi, analisis data, atau visualisasi, tulis kode Python | |
| - Untuk pertanyaan umum, gunakan pengetahuan kamu untuk memberikan jawaban yang membantu | |
| - Selalu bersikap membantu dan pilih pendekatan yang paling tepat untuk setiap pertanyaan | |
| """ | |
| ) | |
| summarizer = AssistantAgent( | |
| "summarizer", | |
| model_client=model_client, | |
| system_message=""" | |
| Kamu bertugas meringkas percakapan dan mengecek apakah sudah jawaban sudah relevan dengan pertanyaan. | |
| - Hasil jawaban akan diubah menjadi audio jadi hindari penggunaan karakter atau simbol khusus. | |
| - Hasil jawaban kamu harus ringkas, praktis, teks tidak panjang. | |
| - Hasil jawaban jika ada, sebisa mungkin ubah angka dan simbol ke teks yang bisa dibaca seperti 1 menjadi satu, + menjadi tambah. | |
| - Hasil jawaban dalam bahasa Indonesia, bisa dikombinasikan dengan inggris jika diperlukan untuk penjelasan. | |
| - Jika hasil jawaban sudah memberikan jawaban yang relevan, kamu bisa tambahkan diakhir "TERMINATE". | |
| """ | |
| ) | |
| from autogen_agentchat.conditions import TextMentionTermination, MaxMessageTermination | |
| termination = TextMentionTermination("TERMINATE") | MaxMessageTermination(5) | |
| team_agent = RoundRobinGroupChat([assistant, summarizer], termination) | |
| current_task = None | |
| current_token = None | |
| async def run_team_task(team, task_desc): | |
| global current_task, current_token | |
| # Cancel previous task if still running | |
| if current_task and not current_task.done(): | |
| if current_token: | |
| current_token.cancel() | |
| try: | |
| await current_task | |
| except Exception as e: | |
| print(f"Previous task cancelled: {e}") | |
| # Start a new cancellation token and run the team task | |
| current_token = CancellationToken() | |
| current_task = asyncio.create_task( | |
| team.run(task=task_desc, cancellation_token=current_token) | |
| ) | |
| return await current_task | |
| # test_questions = [ | |
| # "Berapa suhu di Jakarta besok?", | |
| # "Apa itu machine learning?", | |
| # "Hitung deret fibonacci hingga 10 angka", | |
| # "Berapa 20 + 40 / 5?" | |
| # ] | |
| # user_input = test_questions[0] | |
| # response = await team.run(task=user_input) |