File size: 7,401 Bytes
0e09629
8bb6b63
 
321be4e
72139be
 
 
 
 
8bb6b63
321be4e
8476b78
 
 
72139be
321be4e
72139be
321be4e
72139be
8bb6b63
72139be
 
 
 
 
 
 
 
321be4e
72139be
 
 
 
 
 
 
 
 
321be4e
 
72139be
 
321be4e
8476b78
72139be
321be4e
 
 
 
 
 
 
 
 
 
 
 
 
 
72139be
321be4e
8476b78
 
 
321be4e
72139be
321be4e
8476b78
8bb6b63
321be4e
8bb6b63
 
 
0f0407d
8476b78
321be4e
72139be
01990d8
 
 
321be4e
01990d8
 
8476b78
321be4e
72139be
321be4e
 
72139be
 
321be4e
72139be
8476b78
72139be
 
8476b78
 
 
321be4e
8476b78
321be4e
72139be
321be4e
8476b78
 
321be4e
8bb6b63
72139be
b5a485f
 
b4aa9f9
 
321be4e
8bb6b63
321be4e
 
 
 
 
8bb6b63
 
0f0407d
321be4e
c72759d
321be4e
 
 
 
 
 
 
 
 
72139be
01990d8
 
321be4e
 
8bb6b63
72139be
01990d8
321be4e
 
 
0ab4ce4
beaf568
24904a3
a26b3e0
beaf568
a26b3e0
b5a485f
 
321be4e
 
 
 
 
b5a485f
 
321be4e
b5a485f
321be4e
beaf568
 
b5a485f
beaf568
01990d8
321be4e
 
 
 
 
 
 
 
8bb6b63
24904a3
b4aa9f9
321be4e
 
 
 
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
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
import gradio as gr
import os
import time
from groq import Groq
import requests
from bs4 import BeautifulSoup
from urllib.parse import urljoin, urlparse
import re
import json

# API Setup
GROQ_API_KEY = os.getenv("GROQ_API_KEY")
if not GROQ_API_KEY:
    raise ValueError("GROQ_API_KEY environment variable is not set.")

client = Groq(api_key=GROQ_API_KEY)

# Helper Functions
def is_valid_url(url):
    try:
        result = urlparse(url)
        return all([result.scheme, result.netloc])
    except ValueError:
        return False

def fetch_webpage(url):
    try:
        response = requests.get(url, timeout=10)
        response.raise_for_status()
        return response.text
    except requests.exceptions.RequestException as e:
        return f"Error fetching URL: {e}"

def extract_text_from_html(html):
    soup = BeautifulSoup(html, 'html.parser')
    text = soup.get_text(separator=' ', strip=True)
    return text

# Chat Logic
async def chat_with_agent(user_input, chat_history):
    start_time = time.time()
    try:
        # Prepare chat history
        formatted_history = "\n".join([f"User: {msg[0]}\nAI: {msg[1]}" for msg in chat_history[-10:]])

        system_prompt = """You are TaskMaster, an advanced agentic AI designed to help users accomplish their goals through:
        1. Understanding and breaking down complex tasks
        2. Using available tools effectively
        3. Providing creative solutions with occasional humor
        4. Maintaining context and adapting to user needs
        
        Available tools:
        - Web scraping (URL required)
        - Internet search simulation
        
        You can take actions using:
        Action: take_action, Parameters: {"action":"scrape", "url":"https://example.com"}
        Action: take_action, Parameters: {"action":"search_internet", "query":"search query"}"""

        messages = [
            {"role": "system", "content": system_prompt},
            {"role": "user", "content": user_input}
        ]

        completion = client.chat.completions.create(
            messages=messages,
            temperature=0.7,
            max_tokens=2048,
            stream=True,
            stop=None
        )

        response = ""
        chain_of_thought = ""
        tool_execution_count = 0
        
        for chunk in completion:
            if chunk.choices[0].delta and chunk.choices[0].delta.content:
                content = chunk.choices[0].delta.content
                response += content
                
                if "Chain of Thought:" in content:
                    chain_of_thought += content.split("Chain of Thought:", 1)[-1]

                if "Action:" in content and tool_execution_count < 3:
                    action_match = re.search(r"Action: (\w+), Parameters: (\{.*\})", content)
                    if action_match:
                        tool_execution_count += 1
                        action = action_match.group(1)
                        parameters = json.loads(action_match.group(2))
                        
                        if action == "take_action":
                            if parameters.get("action") == "scrape":
                                url = parameters.get("url")
                                if is_valid_url(url):
                                    html_content = fetch_webpage(url)
                                    if not html_content.startswith("Error"):
                                        webpage_text = extract_text_from_html(html_content)
                                        response += f"\nWebpage Content: {webpage_text[:1000]}...\n"
                                    else:
                                        response += f"\nError scraping webpage: {html_content}\n"
                                else:
                                    response += "\nInvalid URL provided.\n"
                            elif parameters.get("action") == "search_internet":
                                query = parameters.get("query")
                                response += f"\nSearching for: {query}\nSimulated search results would appear here.\n"

        compute_time = time.time() - start_time
        token_usage = len(user_input.split()) + len(response.split())
        return response, chain_of_thought, f"Compute Time: {compute_time:.2f} seconds", f"Tokens used: {token_usage}"

    except Exception as e:
        return f"Error: {str(e)}", "", "Error occurred", ""

# Gradio Interface
def create_interface():
    with gr.Blocks(theme=gr.themes.Soft()) as demo:
        gr.Markdown("""# 🤖 TaskMaster: Your AI Assistant
        Let me help you accomplish your goals through intelligent task execution!""")

        with gr.Row():
            with gr.Column(scale=6):
                chat_history = gr.Chatbot(label="Chat History", height=600)
            with gr.Column(scale=2):
                compute_time = gr.Textbox(label="Performance Metrics", interactive=False)
                chain_of_thought_display = gr.Textbox(label="Reasoning Process", interactive=False, lines=10)
                token_usage_display = gr.Textbox(label="Resource Usage", interactive=False)

        user_input = gr.Textbox(
            label="Your Request",
            placeholder="What would you like me to help you with?",
            lines=2
        )

        with gr.Row():
            send_button = gr.Button("Send", variant="primary")
            clear_button = gr.Button("Clear")
            export_button = gr.Button("Save Chat")

        async def handle_chat(chat_history, user_input):
            if not user_input.strip():
                return chat_history, "", "", ""
            
            ai_response, chain_of_thought, compute_info, token_usage = await chat_with_agent(user_input, chat_history)
            chat_history.append((user_input, ai_response))
            return chat_history, chain_of_thought, compute_info, token_usage

        def clear_chat():
            return [], "", "", ""

        def export_chat(chat_history):
            if not chat_history:
                return "No chat history to export.", ""
            
            filename = f"taskmaster_chat_{int(time.time())}.txt"
            chat_text = "\n".join([f"User: {item[0]}\nAI: {item[1]}\n" for item in chat_history])
            
            with open(filename, "w") as file:
                file.write(chat_text)
            return f"Chat saved to {filename}", ""

        # Event handlers
        send_button.click(handle_chat, inputs=[chat_history, user_input], outputs=[chat_history, chain_of_thought_display, compute_time, token_usage_display])
        clear_button.click(clear_chat, outputs=[chat_history, chain_of_thought_display, compute_time, token_usage_display])
        export_button.click(export_chat, inputs=[chat_history], outputs=[compute_time, chain_of_thought_display])
        user_input.submit(handle_chat, inputs=[chat_history, user_input], outputs=[chat_history, chain_of_thought_display, compute_time, token_usage_display])

        gr.Markdown("""### 🌟 Capabilities:
        - Task Analysis & Breakdown
        - Web Information Retrieval
        - Creative Problem-Solving
        - Context-Aware Responses
        - Performance Tracking
        - Chat Export
        """)

    return demo

# Launch the application
if __name__ == "__main__":
    demo = create_interface()
    demo.launch()