File size: 4,716 Bytes
8ef6562
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6795e79
8ef6562
6795e79
 
8ef6562
6795e79
8ef6562
 
6795e79
8ef6562
 
 
 
 
 
 
 
 
 
 
2d3e706
8ef6562
2d3e706
8ef6562
2d3e706
8ef6562
14db953
8ef6562
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2d3e706
8ef6562
 
 
 
 
14db953
 
 
8ef6562
14db953
8ef6562
 
 
 
 
 
 
 
 
6795e79
8ef6562
 
6795e79
8ef6562
 
6795e79
8ef6562
6795e79
 
 
 
 
 
8ef6562
6795e79
8ef6562
 
 
2d3e706
8ef6562
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
"""Simple RobotPai App without OAuth for Hugging Face Spaces"""
import os
import gradio as gr
from langchain_core.messages import HumanMessage
from agent import build_graph

class SimpleAgent:
    """A simple langgraph agent for Hugging Face Spaces."""
    def __init__(self, provider="google"):
        print(f"SimpleAgent initialized with {provider} provider.")
        try:
            self.graph = build_graph(provider=provider)
            print("Graph built successfully!")
        except Exception as e:
            print(f"Error building graph: {e}")
            self.graph = None

    def __call__(self, question: str) -> str:
        if not self.graph:
            return "โŒ Error: Agent not properly initialized. Please check API keys in Space settings."
        
        try:
            print(f"Agent received question: {question[:100]}...")
            # Wrap the question in a HumanMessage from langchain_core
            messages = [HumanMessage(content=question)]
            result = self.graph.invoke({"messages": messages})
            answer = result['messages'][-1].content
            return answer
        except Exception as e:
            return f"โŒ Error processing question: {str(e)}\n\nPlease check that your API keys are properly configured in the Space settings."

# Force Groq provider to avoid Google rate limits
def get_available_provider():
    """Force Groq provider to avoid Google API rate limits"""
    return "groq"  # Always use Groq to avoid Google rate limits

# Initialize agent with Groq provider
provider = get_available_provider()
print(f"๐Ÿค– Initializing RobotPai with {provider} provider...")
print("๐Ÿ“ Note: Using Groq to avoid Google API rate limits")
agent = SimpleAgent(provider=provider)

def chat_with_agent(message, history):
    """Chat function for Gradio interface"""
    if not message.strip():
        return "Please enter a question or message."
    
    response = agent(message)
    return response

# Create Gradio interface
with gr.Blocks(title="incligen", theme=gr.themes.Soft()) as demo:
    gr.Markdown("""
    # ๐Ÿค– incligen
    
    Welcome to incligen! I'm an AI agent powered by LangGraph that can help you with:
    
    - ๐Ÿงฎ **Math calculations** (add, subtract, multiply, divide, modulus, square root, power, absolute)
    - ๐Ÿค” **General questions** using advanced AI
    - ๐Ÿ” **Web search** (when Tavily API is configured)
    - ๐Ÿ“š **Wikipedia search** (when available)
    - ๐Ÿ“„ **Arxiv research** (when available)
    
    Just type your question below and I'll do my best to help!
    """)
    
    # Status indicator
    if agent.graph:
        gr.Markdown("โœ… **Status**: Agent is ready and operational!")
    else:
        gr.Markdown("โŒ **Status**: Agent initialization failed. Please check API key configuration.")
    
    # Chat interface
    chatbot = gr.ChatInterface(
        fn=chat_with_agent,
        title="Chat with incligen",
        description="Ask me anything! I can do math, answer questions, and more.",
        examples=[
            "What is 15 + 27?",
            "Calculate 144 divided by 12",
            "What is 25 * 8?",
            "What is the square root of 144?",
            "Calculate 2 to the power of 8",
            "What is the absolute value of -15?",
            "What is the capital of France?",
            "Explain quantum computing in simple terms"
        ],
        retry_btn="๐Ÿ”„ Retry",
        undo_btn="โ†ฉ๏ธ Undo",
        clear_btn="๐Ÿ—‘๏ธ Clear",
    )
    
    gr.Markdown("""
    ---
    ### ๐Ÿ”ง Configuration Notes:
    - **LLM Provider**: Using Groq (optimized for performance and rate limits)
    - **Tools Available**: Math operations, AI reasoning
    - **Search Tools**: Available when API keys are configured

    ### ๐Ÿ”‘ API Keys Required:
    Add these to Space settings for full functionality:
    - `GROQ_API_KEY` (for AI responses - recommended)
    - `TAVILY_API_KEY` (for web search)

    ### โšก Why Groq?
    - **Higher rate limits** than Google free tier
    - **Faster responses** with optimized inference
    - **More reliable** for frequent testing

    Built with [LangGraph](https://langchain-ai.github.io/langgraph/) and [Gradio](https://gradio.app)
    """)

if __name__ == "__main__":
    print("\n" + "="*60)
    print("๐Ÿš€ Starting incligen on Hugging Face Spaces")
    print("="*60)
    
    # Check configuration
    if agent.graph:
        print("โœ… Agent initialized successfully!")
        print(f"๐Ÿ”ง Using {provider} provider")
    else:
        print("โŒ Agent initialization failed!")
        print("๐Ÿ’ก Please check API keys in Space settings")
    
    print("๐ŸŒ Launching web interface...")
    demo.launch()