Spaces:
Paused

gala-agent / app.py
ApeMaster's picture
Update app.py
6054245 verified
Raw History Blame Contribute Delete
6.58 kB
import os
import traceback
import gradio as gr
from smolagents import (
CodeAgent,
OpenAIModel,
DuckDuckGoSearchTool
)
from tools import (
WeatherInfoTool,
HubStatsTool,
GuestInfoRetrieverTool
)
# ==================================================
# GALA - GROUNDED AGENTIC LEARNING ASSISTANT
# ==================================================
print("Initializing GALA...")
# ==================================================
# 1. HUGGING FACE AUTHENTICATION
# ==================================================
HF_TOKEN = os.environ.get("HF_TOKEN")
if not HF_TOKEN:
raise ValueError(
"HF_TOKEN is missing. Add your Hugging Face token "
"under Settings > Secrets in your Space."
)
# ==================================================
# 2. MODEL CONFIGURATION
# ==================================================
print("Connecting to Hugging Face Inference Providers...")
model = OpenAIModel(
model_id="openai/gpt-oss-120b:fastest",
api_base="https://router.huggingface.co/v1",
api_key=HF_TOKEN,
temperature=0.2,
max_tokens=2048
)
print("Model configured successfully!")
# ==================================================
# 3. TOOL CONFIGURATION
# ==================================================
print("Loading GALA tools...")
guest_retriever = GuestInfoRetrieverTool()
tools = [
DuckDuckGoSearchTool(),
WeatherInfoTool(),
HubStatsTool(),
guest_retriever
]
print("GALA tools loaded successfully!")
# ==================================================
# 4. AGENT CONFIGURATION
# ==================================================
agent = CodeAgent(
tools=tools,
model=model,
add_base_tools=True,
max_steps=8
)
print("GALA initialized successfully!")
# ==================================================
# 5. CONVERSATION HISTORY
# ==================================================
def format_history(history):
if not history:
return ""
conversation = []
for item in history[-10:]:
if isinstance(item, dict):
role = item.get("role", "user")
content = item.get("content", "")
if isinstance(content, list):
content = " ".join(
part.get("text", "")
for part in content
if isinstance(part, dict)
)
if isinstance(content, str) and content.strip():
conversation.append(
f"{role.capitalize()}: {content}"
)
elif isinstance(item, (list, tuple)):
if len(item) >= 2:
user_message = item[0]
assistant_message = item[1]
if user_message:
conversation.append(
f"User: {user_message}"
)
if assistant_message:
conversation.append(
f"Assistant: {assistant_message}"
)
return "\n".join(conversation)
# ==================================================
# 6. GALA CHAT FUNCTION
# ==================================================
def chat_with_gala(message, history):
try:
print(f"GALA received message: {message}")
previous_conversation = format_history(history)
prompt = f"""
You are GALA (Grounded Agentic Learning Assistant).
You are an intelligent AI assistant that can research questions,
retrieve information, and use tools to provide useful answers.
YOUR CAPABILITIES:
1. Web Research
Use your web search tool to research questions and find information.
2. Weather Information
Use your weather tool to retrieve weather information for a city.
3. Hugging Face Model Research
Use your Hugging Face Hub tool to find machine learning models
and provide information about their popularity.
4. Guest Information Retrieval
Use your guest information retrieval tool to search the
Hugging Face Agents Course guest dataset.
INSTRUCTIONS:
- Use tools when they are relevant to the user's question.
- Do not invent information or pretend to have used a tool.
- Clearly distinguish retrieved facts from your own explanations.
- Give helpful, organized, and understandable responses.
- If a tool fails, explain that you could not retrieve the information.
- Remember the previous conversation when answering follow-up questions.
PREVIOUS CONVERSATION:
{previous_conversation}
CURRENT USER QUESTION:
{message}
Respond directly to the current question.
"""
response = agent.run(prompt)
print("GALA successfully generated a response.")
return str(response)
except Exception as e:
print("GALA ERROR:")
traceback.print_exc()
return (
"I'm sorry, but I encountered an error while "
"processing your request.\n\n"
f"Error details: {str(e)}"
)
# ==================================================
# 7. GRADIO INTERFACE
# ==================================================
with gr.Blocks() as demo:
gr.Markdown(
"""
# 🎩 GALA
### Grounded Agentic Learning Assistant
Welcome to GALA!
I'm an AI assistant powered by smolagents and Hugging Face.
I can research information, retrieve relevant data, and
use specialized tools to help answer your questions.
**What would you like to explore today?**
"""
)
gr.ChatInterface(
fn=chat_with_gala,
chatbot=gr.Chatbot(
height=500,
placeholder="Your conversation with GALA will appear here."
),
textbox=gr.Textbox(
placeholder="Ask GALA a question...",
container=False,
scale=7
),
title="GALA AI Assistant",
description="Powered by Apes of AI technology.",
examples=[
"Hello GALA. Introduce yourself.",
"What is the weather in Las Vegas?",
"Find popular language models on Hugging Face.",
"Who are the invited guests in the Agents Course dataset?",
"Search the web for recent developments in AI agents."
]
)
# ==================================================
# 8. LAUNCH APPLICATION
# ==================================================
if __name__ == "__main__":
demo.queue(default_concurrency_limit=1)
demo.launch(
theme=gr.themes.Soft(
primary_hue="blue",
secondary_hue="slate"
)
)