Whshhs / app.py
Athspi's picture
Update app.py
a517846 verified
raw
history blame
4.44 kB
import os
import gradio as gr
from google import genai
from google.genai import types
import requests
import markdownify
from urllib.robotparser import RobotFileParser
from urllib.parse import urlparse
# Configure browser tools
def can_crawl_url(url: str, user_agent: str = "*") -> bool:
"""Check robots.txt permissions for a URL"""
try:
parsed_url = urlparse(url)
robots_url = f"{parsed_url.scheme}://{parsed_url.netloc}/robots.txt"
rp = RobotFileParser(robots_url)
rp.read()
return rp.can_fetch(user_agent, url)
except Exception as e:
print(f"Error checking robots.txt: {e}")
return False
def load_page(url: str) -> str:
"""Load webpage content as markdown"""
if not can_crawl_url(url):
return f"URL {url} failed robots.txt check"
try:
response = requests.get(url, timeout=10)
return markdownify.markdownify(response.text)
except Exception as e:
return f"Error loading page: {str(e)}"
# Initialize Gemini client
client = genai.Client(api_key=os.environ.get("GEMINI_API_KEY"))
MODEL = "gemini-2.0-flash"
TOOL_CONFIGS = {
"web": [
types.Tool(
function_declarations=[
types.FunctionDeclaration(
name="load_page",
description="Load webpage content as markdown",
parameters={
"type": "object",
"properties": {
"url": {"type": "string", "description": "Full URL to load"}
},
"required": ["url"]
}
)
]
),
types.Tool(google_search=types.GoogleSearch())
],
"code": [
types.Tool(code_execution=types.ToolCodeExecution())
]
}
SYSTEM_INSTRUCTION = """You are an AI assistant. Choose appropriate tools based on the query:
- Use web tools for real-time information
- Use code execution for calculations/analysis
- Never combine search with code execution"""
def format_response(parts):
"""Format response parts with proper Markdown formatting"""
formatted = []
for part in parts:
if part.text:
formatted.append(part.text)
if part.executable_code:
formatted.append(f"```python\n{part.executable_code.code}\n```")
if part.code_execution_result:
formatted.append(f"**Result**:\n```\n{part.code_execution_result.output}\n```")
return "\n\n".join(formatted)
def select_tools(query: str) -> list:
"""Select appropriate tools based on query content"""
if any(keyword in query.lower() for keyword in ["plot", "calculate", "simulate", "algorithm"]):
return TOOL_CONFIGS["code"]
return TOOL_CONFIGS["web"]
def generate_response(user_input):
try:
if not user_input.strip():
raise ValueError("Please enter a valid query")
selected_tools = select_tools(user_input)
response = client.models.generate_content(
model=MODEL,
contents=[user_input],
config=types.GenerateContentConfig(
temperature=0.7,
tools=selected_tools,
system_instruction=SYSTEM_INSTRUCTION
)
)
return format_response(response.candidates[0].content.parts)
except Exception as e:
return f"Error: {str(e)}"
# Create Gradio interface
with gr.Blocks(title="Gemini AI Assistant") as demo:
gr.Markdown("# πŸš€ Gemini AI Assistant")
gr.Markdown("Web β€’ Code β€’ Data Analysis")
with gr.Row():
input_box = gr.Textbox(
label="Your Query",
placeholder="Ask anything...",
lines=3,
max_lines=10
)
output_box = gr.Markdown(
label="Response",
elem_classes="markdown-output"
)
with gr.Row():
submit_btn = gr.Button("Submit", variant="primary")
clear_btn = gr.Button("Clear")
def clear():
return ["", ""]
submit_btn.click(
fn=generate_response,
inputs=input_box,
outputs=output_box
)
clear_btn.click(
fn=clear,
inputs=[],
outputs=[input_box, output_box]
)
if __name__ == "__main__":
demo.launch(server_name="0.0.0.0", server_port=7860)