Spaces:
Sleeping
Sleeping
Create app.py
Browse files
app.py
ADDED
|
@@ -0,0 +1,64 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import gradio as gr
|
| 3 |
+
from google import genai
|
| 4 |
+
from apscheduler.schedulers.background import BackgroundScheduler
|
| 5 |
+
|
| 6 |
+
GEMINI_KEY = os.environ.get("GEMINI_API_KEY")
|
| 7 |
+
|
| 8 |
+
def get_client():
|
| 9 |
+
if GEMINI_KEY:
|
| 10 |
+
return genai.Client(api_key=GEMINI_KEY)
|
| 11 |
+
return None
|
| 12 |
+
|
| 13 |
+
def agent_background_task():
|
| 14 |
+
print("Agent checking background tasks...")
|
| 15 |
+
try:
|
| 16 |
+
client = get_client()
|
| 17 |
+
if client:
|
| 18 |
+
response = client.models.generate_content(
|
| 19 |
+
model='gemini-2.5-flash',
|
| 20 |
+
contents='Briefly simulate an agent task update.',
|
| 21 |
+
)
|
| 22 |
+
print(f"Agent update: {response.text}")
|
| 23 |
+
except Exception as e:
|
| 24 |
+
print(f"Background error: {e}")
|
| 25 |
+
|
| 26 |
+
scheduler = BackgroundScheduler()
|
| 27 |
+
scheduler.add_job(func=agent_background_task, trigger="interval", minutes=15)
|
| 28 |
+
scheduler.start()
|
| 29 |
+
|
| 30 |
+
def chat_with_agent(message, history):
|
| 31 |
+
client = get_client()
|
| 32 |
+
if not client:
|
| 33 |
+
yield "⚠️ Please add your GEMINI_API_KEY in Settings Secrets!"
|
| 34 |
+
return
|
| 35 |
+
|
| 36 |
+
try:
|
| 37 |
+
formatted_contents = []
|
| 38 |
+
for human_msg, ai_msg in history:
|
| 39 |
+
formatted_contents.append({"role": "user", "parts": [{"text": human_msg}]})
|
| 40 |
+
formatted_contents.append({"role": "model", "parts": [{"text": ai_msg}]})
|
| 41 |
+
|
| 42 |
+
formatted_contents.append({"role": "user", "parts": [{"text": message}]})
|
| 43 |
+
|
| 44 |
+
response = client.models.generate_content_stream(
|
| 45 |
+
model='gemini-2.5-flash',
|
| 46 |
+
contents=formatted_contents
|
| 47 |
+
)
|
| 48 |
+
|
| 49 |
+
partial_message = ""
|
| 50 |
+
for chunk in response:
|
| 51 |
+
if chunk.text:
|
| 52 |
+
partial_message += chunk.text
|
| 53 |
+
yield partial_message
|
| 54 |
+
except Exception as e:
|
| 55 |
+
yield f"Error processing prompt: {str(e)}"
|
| 56 |
+
|
| 57 |
+
demo = gr.ChatInterface(
|
| 58 |
+
fn=chat_with_agent,
|
| 59 |
+
title="AI Agent Server Hub",
|
| 60 |
+
description="Running entirely on 16GB free RAM. Designed for heavy multi-step loops."
|
| 61 |
+
)
|
| 62 |
+
|
| 63 |
+
if __name__ == "__main__":
|
| 64 |
+
demo.queue().launch(server_name="0.0.0.0", server_port=7860)
|