Spaces:
Sleeping
Sleeping
File size: 5,972 Bytes
f081f15 7b26d45 f081f15 7b26d45 f081f15 7b26d45 7173c28 |
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 183 184 185 186 187 188 |
# Install required packages
# !pip install agno gradio reportlab groq pillow tavily-python lancedb -q
# Install required packages
# !pip install agno gradio reportlab groq pillow tavily-python lancedb python-dotenv -q
# Import libraries
import os
from agno.agent import Agent
from agno.models.groq import Groq
from agno.tools.tavily import TavilyTools
from agno.knowledge.pdf_url import PDFUrlKnowledgeBase
from agno.vectordb.lancedb import LanceDb, SearchType
from agno.embedder.google import GeminiEmbedder
from reportlab.lib.pagesizes import letter
from reportlab.pdfgen import canvas
import datetime
from PIL import Image
import gradio as gr
from dotenv import load_dotenv
import base64
# Load environment variables (optional in Colab; set directly if preferred)
load_dotenv()
# Set API keys (replace with your actual keys or use os.getenv in a .env file)
groq_api_key = os.getenv("GROQ_API_KEY")
tavily_api_key = os.getenv("TAVILY_API_KEY")
gemini_api_key = os.getenv("GEMINI_API_KEY")
print(groq_api_key)
# Setup knowledge base with Colab-compatible path
def setup_knowledge_base(file_paths=None):
if not file_paths:
file_paths = []
knowledge = PDFUrlKnowledgeBase(
urls=file_paths,
vector_db=LanceDb(
uri="lancedb_data", # Colab-friendly path
table_name="docs",
search_type=SearchType.hybrid,
embedder=GeminiEmbedder(api_key=gemini_api_key)
)
)
if file_paths:
knowledge.load()
return knowledge
# Define PDF generation tool
def generate_pdf(text):
filename = "output.pdf"
c = canvas.Canvas(filename, pagesize=letter)
c.drawString(100, 750, text[:100])
c.save()
return filename
# Image analysis tool
# def analyze_images(image_paths):
# if not isinstance(image_paths, list):
# image_paths = [image_paths]
# descriptions = []
# for path in image_paths:
# img = Image.open(path)
# descriptions.append(f"{os.path.basename(path)}: size={img.size}px")
# return "\n".join(descriptions)
def analyze_images(image_paths):
if not isinstance(image_paths, list):
image_paths = [image_paths]
descriptions = []
for path in image_paths:
with open(path, "rb") as img_file:
img_base64 = base64.b64encode(img_file.read()).decode("utf-8")
descriptions.append(f"Image {os.path.basename(path)} analyzed (size via PIL: {Image.open(path).size}px)")
return "\n".join(descriptions)
# Define Agents
web_agent = Agent(
model=Groq(id="gemma2-9b-it"),
description="Web search expert",
instructions=["Use Tavily to search the web."],
tools=[TavilyTools()],
markdown=True
)
date_agent = Agent(
model=Groq(id="gemma2-9b-it"),
description="Date-time expert",
markdown=True
)
rag_agent = Agent(
model=Groq(id="gemma2-9b-it"),
description="Knowledge retrieval expert",
instructions=["Search the knowledge base."],
knowledge=setup_knowledge_base(),
markdown=True
)
pdf_agent = Agent(
model=Groq(id="gemma2-9b-it"),
description="PDF creator",
tools=[generate_pdf],
markdown=True
)
image_agent = Agent(
model=Groq(id="llama-3.2-90b-vision-preview"),
description="Image analyzer",
tools=[analyze_images],
markdown=True
)
# Coordinator class
class Coordinator:
def __init__(self):
self.team = {
"Web Browsing": web_agent,
"Date-Time": date_agent,
"RAG": rag_agent,
"PDF Generation": pdf_agent,
"Image Analysis": image_agent
}
self.chat_history = []
def process_query(self, query, tool, files=None):
self.chat_history.append({"role": "user", "content": query})
response_parts = []
# Handle uploaded files
pdf_files = [f.name for f in files or [] if f.name.lower().endswith(".pdf")]
img_files = [f.name for f in files or [] if f.name.lower().endswith((".png", ".jpg", ".jpeg"))]
if pdf_files:
rag_agent.knowledge = setup_knowledge_base(pdf_files)
response_parts.append(f"✅ Loaded {len(pdf_files)} PDF(s).")
if img_files:
img_response = image_agent.run(img_files).content
print("img_response", img_response)
response_parts.append(img_response)
if response_parts:
response = "\n".join(response_parts)
else:
selected_agent = self.team.get(tool, rag_agent)
if tool == "Date-Time":
response = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
else:
# Extract the content from the RunResponse object
response_obj = selected_agent.run(query)
response = response_obj.content if hasattr(response_obj, "content") else str(response_obj)
self.chat_history.append({"role": "assistant", "content": response})
return response
coordinator = Coordinator()
# Gradio Interface
def chat_interface(query, tool, files, history):
if not history:
history = []
response = coordinator.process_query(query, tool, files)
history.append((query, response))
return history, history
# Launch Gradio in Colab with public link
with gr.Blocks(title="Multimodal AI Chat") as demo:
gr.Markdown("# 🤖 Multimodal AI Chat")
chatbot = gr.Chatbot()
with gr.Row():
query_input = gr.Textbox(label="Query")
tool_dropdown = gr.Dropdown(
choices=["Web Browsing", "Date-Time", "RAG", "PDF Generation", "Image Analysis"],
value="RAG",
label="Select Tool"
)
file_upload = gr.File(file_count="multiple", file_types=[".pdf", ".png", ".jpg", ".jpeg"])
submit_btn = gr.Button("Submit")
submit_btn.click(
chat_interface,
[query_input, tool_dropdown, file_upload, chatbot],
[chatbot, chatbot]
)
if __name__ == "__main__":
demo.launch()
|