intellijmind / app.py
Threatthriver's picture
Update app.py
321be4e verified
raw
history blame
7.4 kB
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()