Certainly! Below is a comprehensive Gradio application that creates a user interface with two distinct tabs:
-
Tab 1: Chat with Llama3.2-Vision
- Features:
- Chat Interface: Allows users to interact with the
llama3.2-vision model.
- Image Upload: Users can upload images which the model can process alongside text inputs.
-
Tab 2: Chat with Llama3.1
- Features:
- Chat Interface: Facilitates interaction with the
llama3.1 model.
- Web Search Tool: Enables the model to perform real-time web searches using the DuckDuckGo search engine.
- Image Generation Tool: Allows the model to generate images based on user prompts. For demonstration purposes, it uploads a predefined
image.png.
Overview of the Implementation
-
Libraries Used:
gradio: For building the web interface.
langchain_ollama: To interface with the Llama models.
langchain_core: For handling messages and tools.
PIL: For image processing.
base64, io, and os: For handling image encoding and file operations.
-
Key Components:
- Tools:
search_web: Uses DuckDuckGo to fetch real-time information based on user queries.
generate_image: Generates a demo image (image.png) and returns its path.
- Models:
llm_image: Initialized with llama3.2-vision for handling multimodal inputs (text and images).
llm_text: Initialized with llama3.1 and equipped with the search_web and generate_image tools.
- Helper Functions:
convert_image_to_base64: Converts PIL Image objects to base64-encoded strings for embedding in chat responses.
- Chat Handlers:
chatbot_response_tab1: Handles interactions in Tab 1, supporting both text and image inputs.
chatbot_response_tab2: Manages interactions in Tab 2, utilizing tools like web search and image generation.
-
Gradio Interface:
- Organized using Gradio's
Blocks API with two separate tabs.
- Each tab maintains its own chat history and input mechanisms.
- Streaming responses are supported to provide real-time feedback from the models.
Complete Code Implementation
import gradio as gr
from langchain_ollama import ChatOllama
from langchain_core.messages import HumanMessage, AIMessage, SystemMessage
from langchain_core.tools import tool
from langchain_community.tools import DuckDuckGoSearchRun
import base64
from io import BytesIO
from PIL import Image
import os
# ---------------------------------------------------------------
# Define the web search tool using the @tool decorator
@tool
def search_web(query: str) -> str:
"""Use this tool to search the web for real-time information based on a query."""
search = DuckDuckGoSearchRun()
return search.run(query)
# Define the image generation tool using the @tool decorator
@tool
def generate_image(prompt: str) -> str:
"""
Generates an image based on the prompt and returns the file path.
For demonstration, it returns a predefined image.
"""
# In a real implementation, integrate with an image generation API.
# Here, we'll create a simple demo image.
img = Image.new('RGB', (200, 100), color=(73, 109, 137))
d = ImageDraw.Draw(img)
draw_text = f"Prompt: {prompt}"
d.text((10, 40), draw_text, fill=(255, 255, 0))
img_path = "image.png"
img.save(img_path)
return img_path
# ---------------------------------------------------------------
# Initialize the models
# llama3.2-vision for image inputs (does not support tools)
llm_image = ChatOllama(
model='llama3.2-vision',
temperature=0.8,
# Add other parameters as needed
)
# llama3.1 with tool calling capabilities for text inputs
llm_text = ChatOllama(
model='llama3.1',
temperature=0.8,
# Add other parameters as needed
).bind_tools([search_web, generate_image])
# ---------------------------------------------------------------
def convert_image_to_base64(image):
"""
Convert a PIL Image to a base64 encoded string.
"""
buffered = BytesIO()
image.save(buffered, format="PNG")
img_str = base64.b64encode(buffered.getvalue()).decode("utf-8")
return img_str
# ---------------------------------------------------------------
def chatbot_response_tab1(message, history):
"""
Handle responses for Tab 1: Chat with llama3.2-vision.
Supports both text and image inputs.
"""
has_image = False
has_text = False
if isinstance(message, dict):
has_image = message.get("image") is not None or message.get("files") is not None
has_text = message.get("text") is not None and message.get("text").strip() != ""
elif isinstance(message, str):
has_text = message.strip() != ""
elif isinstance(message, Image.Image):
has_image = True
# Choose the appropriate model
if has_image:
llm = llm_image
else:
llm = llm_text # Fallback to text model if necessary
# Prepare the conversation history for the model
model_messages = []
def create_content_parts(msg):
content_parts = []
if isinstance(msg, dict):
if msg.get("text") and msg.get("text").strip() != "":
content_parts.append({"type": "text", "text": msg["text"]})
if msg.get("image"):
# Handle image as PIL Image object
image_b64 = convert_image_to_base64(msg["image"])
content_parts.append({
"type": "image_url",
"image_url": f"data:image/png;base64,{image_b64}",
})
if msg.get("files"):
for file_path in msg["files"]:
# Open the image file
try:
if os.path.exists(file_path):
image = Image.open(file_path)
image_b64 = convert_image_to_base64(image)
content_parts.append({
"type": "image_url",
"image_url": f"data:image/png;base64,{image_b64}",
})
else:
print(f"File not found: {file_path}")
except Exception as e:
print(f"Error opening image file {file_path}: {e}")
elif isinstance(msg, str):
if msg.strip() != "":
content_parts.append({"type": "text", "text": msg})
elif isinstance(msg, Image.Image):
# msg is an image
image_b64 = convert_image_to_base64(msg)
content_parts.append({
"type": "image_url",
"image_url": f"data:image/png;base64,{image_b64}",
})
return content_parts
# Convert history to the format expected by the model
for user_msg, bot_msg in history:
# Handle user's previous messages
user_content_parts = create_content_parts(user_msg)
if user_content_parts:
model_messages.append(HumanMessage(content=user_content_parts))
# Handle bot's previous messages
if isinstance(bot_msg, str):
bot_content_parts = [{"type": "text", "text": bot_msg}]
model_messages.append(AIMessage(content=bot_content_parts))
elif isinstance(bot_msg, dict) or isinstance(bot_msg, Image.Image):
bot_content_parts = create_content_parts(bot_msg)
if bot_content_parts:
model_messages.append(AIMessage(content=bot_content_parts))
# Handle the latest message from the user
user_content_parts = create_content_parts(message)
if user_content_parts:
model_messages.append(HumanMessage(content=user_content_parts))
# If using llm_text, add a system message to instruct the assistant
if llm == llm_text:
system_prompt = (
"You are a helpful assistant. "
"You have access to the following tools:\n\n"
"1. **search_web**: Use this tool to search the web for real-time information based on a query.\n"
"2. **generate_image**: Use this tool to generate an image based on a prompt.\n\n"
"Use these tools whenever necessary to provide accurate and up-to-date answers."
)
model_messages.insert(0, SystemMessage(content=system_prompt))
# Generate the response using the model and stream it
response = ""
for chunk in llm.stream(model_messages):
if hasattr(chunk, 'content'):
response += chunk.content
yield response # Stream the response to Gradio
else:
continue
# ---------------------------------------------------------------
def chatbot_response_tab2(message, history):
"""
Handle responses for Tab 2: Chat with llama3.1.
Utilizes tools like web search and image generation.
"""
has_image = False
has_text = False
if isinstance(message, dict):
has_image = message.get("image") is not None or message.get("files") is not None
has_text = message.get("text") is not None and message.get("text").strip() != ""
elif isinstance(message, str):
has_text = message.strip() != ""
elif isinstance(message, Image.Image):
has_image = True
# Choose the appropriate model
if has_image:
llm = llm_image # Depending on requirements, you might use llm_image here
else:
llm = llm_text
# Prepare the conversation history for the model
model_messages = []
def create_content_parts(msg):
content_parts = []
if isinstance(msg, dict):
if msg.get("text") and msg.get("text").strip() != "":
content_parts.append({"type": "text", "text": msg["text"]})
if msg.get("image"):
# Handle image as PIL Image object
image_b64 = convert_image_to_base64(msg["image"])
content_parts.append({
"type": "image_url",
"image_url": f"data:image/png;base64,{image_b64}",
})
if msg.get("files"):
for file_path in msg["files"]:
# Open the image file
try:
if os.path.exists(file_path):
image = Image.open(file_path)
image_b64 = convert_image_to_base64(image)
content_parts.append({
"type": "image_url",
"image_url": f"data:image/png;base64,{image_b64}",
})
else:
print(f"File not found: {file_path}")
except Exception as e:
print(f"Error opening image file {file_path}: {e}")
elif isinstance(msg, str):
if msg.strip() != "":
content_parts.append({"type": "text", "text": msg})
elif isinstance(msg, Image.Image):
# msg is an image
image_b64 = convert_image_to_base64(msg)
content_parts.append({
"type": "image_url",
"image_url": f"data:image/png;base64,{image_b64}",
})
return content_parts
# Convert history to the format expected by the model
for user_msg, bot_msg in history:
# Handle user's previous messages
user_content_parts = create_content_parts(user_msg)
if user_content_parts:
model_messages.append(HumanMessage(content=user_content_parts))
# Handle bot's previous messages
if isinstance(bot_msg, str):
bot_content_parts = [{"type": "text", "text": bot_msg}]
model_messages.append(AIMessage(content=bot_content_parts))
elif isinstance(bot_msg, dict) or isinstance(bot_msg, Image.Image):
bot_content_parts = create_content_parts(bot_msg)
if bot_content_parts:
model_messages.append(AIMessage(content=bot_content_parts))
# Handle the latest message from the user
user_content_parts = create_content_parts(message)
if user_content_parts:
model_messages.append(HumanMessage(content=user_content_parts))
# If using llm_text, add a system message to instruct the assistant
if llm == llm_text:
system_prompt = (
"You are a helpful assistant. "
"You have access to the following tools:\n\n"
"1. **search_web**: Use this tool to search the web for real-time information based on a query.\n"
"2. **generate_image**: Use this tool to generate an image based on a prompt.\n\n"
"Use these tools whenever necessary to provide accurate and up-to-date answers."
)
model_messages.insert(0, SystemMessage(content=system_prompt))
# Generate the response using the model and stream it
response = ""
for chunk in llm.stream(model_messages):
if hasattr(chunk, 'content'):
response += chunk.content
yield response # Stream the response to Gradio
else:
continue
# ---------------------------------------------------------------
# Create the Gradio interface with two tabs
with gr.Blocks() as demo:
gr.Markdown(
"""
# Multimodal Chatbot with Tool Support
Interact with different versions of Llama models with varying capabilities.
"""
)
with gr.Tab("Chat with Llama3.2-Vision"):
gr.Markdown(
"""
## Llama3.2-Vision Chat
- **Chat** with the `llama3.2-vision` model.
- **Upload Images** to process visuals alongside your messages.
"""
)
chat_history1 = gr.State([])
with gr.Row():
with gr.Column(scale=4):
input_text1 = gr.Textbox(
label="Your Message",
placeholder="Type your message here...",
)
with gr.Column(scale=1):
input_image1 = gr.Image(
label="Upload Image",
type="pil",
tool=None
)
send_button1 = gr.Button("Send")
chatbot1 = gr.Chatbot(label="Llama3.2-Vision Chat")
def update_chat1(user_message, user_image, history):
message = {}
if user_message:
message["text"] = user_message
if user_image:
message["image"] = user_image
history = history or []
history.append((message, None))
return history
send_button1.click(
fn=lambda msg, img, hist: chatbot_response_tab1({"text": msg, "image": img}, hist),
inputs=[input_text1, input_image1, chat_history1],
outputs=[chatbot1],
)
with gr.Tab("Chat with Llama3.1"):
gr.Markdown(
"""
## Llama3.1 Chat
- **Chat** with the `llama3.1` model.
- **Search the Web** for real-time information.
- **Generate Images** based on your prompts.
"""
)
chat_history2 = gr.State([])
with gr.Row():
with gr.Column(scale=4):
input_text2 = gr.Textbox(
label="Your Message",
placeholder="Type your message here...",
)
with gr.Column(scale=1):
send_button2 = gr.Button("Send")
chatbot2 = gr.Chatbot(label="Llama3.1 Chat")
with gr.Row():
with gr.Column(scale=6):
search_query = gr.Textbox(
label="Search Query",
placeholder="Enter search query...",
)
with gr.Column(scale=2):
search_button = gr.Button("Search Web")
with gr.Row():
with gr.Column(scale=6):
image_prompt = gr.Textbox(
label="Image Prompt",
placeholder="Enter image description...",
)
with gr.Column(scale=2):
generate_button = gr.Button("Generate Image")
# Define the send action
def send_message_tab2(msg, hist):
return chatbot_response_tab2(msg, hist)
send_button2.click(
fn=lambda msg, hist: send_message_tab2(msg, hist),
inputs=[input_text2, chat_history2],
outputs=[chatbot2],
)
# Define the search action
def perform_search(query, hist):
if not query.strip():
return hist, "Please enter a valid search query."
# Use the search_web tool
result = search_web(query)
hist = hist or []
hist.append((f"Search Query: {query}", f"Search Result: {result}"))
return hist, ""
search_button.click(
fn=perform_search,
inputs=[search_query, chat_history2],
outputs=[chatbot2, search_query],
)
# Define the image generation action
def perform_image_generation(prompt, hist):
if not prompt.strip():
return hist, "Please enter a valid prompt for image generation."
# Use the generate_image tool
image_path = generate_image(prompt)
if os.path.exists(image_path):
image = Image.open(image_path)
hist = hist or []
hist.append((f"Image Prompt: {prompt}", {"image": image}))
return hist, ""
else:
return hist, "Image generation failed."
generate_button.click(
fn=perform_image_generation,
inputs=[image_prompt, chat_history2],
outputs=[chatbot2, image_prompt],
)
# ---------------------------------------------------------------
# Launch the Gradio app
if __name__ == "__main__":
demo.launch()
Detailed Explanation
-
Tools Definition:
search_web: Utilizes the DuckDuckGo search engine to fetch real-time information based on user queries.
generate_image: For demonstration, it creates a simple PNG image with the provided prompt text. In a real-world scenario, you'd integrate this with an actual image generation API like DALL-E or Stable Diffusion.
-
Model Initialization:
llm_image: Configured with the llama3.2-vision model, suitable for handling both text and image inputs.
llm_text: Configured with the llama3.1 model and bound with the search_web and generate_image tools to enhance its capabilities.
-
Helper Function (convert_image_to_base64):
- Converts PIL Image objects into base64-encoded strings, allowing images to be embedded directly within chat responses.
-
Chat Handlers:
chatbot_response_tab1: Manages interactions in Tab 1. It processes incoming messages and images, constructs the conversation history, and streams responses from the llama3.2-vision model.
chatbot_response_tab2: Handles interactions in Tab 2. It leverages the llama3.1 model with access to the defined tools, enabling functionalities like web search and image generation.
-
Gradio Interface Structure:
- Main Blocks:
- Markdown Section: Provides a brief introduction to the application.
- Tabs:
- Tab 1:
- Chatbot Component (
chatbot1): Displays the conversation history.
- Inputs:
- Text Input (
input_text1): For user messages.
- Image Upload (
input_image1): Allows users to upload images.
- Send Button (
send_button1): Triggers the chat response.
Notes and Recommendations
-
Image Generation Enhancement: The generate_image function currently creates a simple image with text. For more advanced image generation, integrate with APIs like OpenAI's DALL-E, Stability AI's Stable Diffusion, or similar services.
-
Error Handling: While basic error handling is implemented (e.g., checking if image.png exists), consider adding more robust error checking and user feedback mechanisms for production environments.
-
Security Considerations: Ensure that file uploads and other user inputs are securely handled to prevent potential vulnerabilities.
-
Scalability: For larger deployments or increased user interactions, consider deploying the application on scalable platforms and managing state efficiently.
This implementation provides a versatile and interactive chatbot interface leveraging the capabilities of different Llama models and associated tools. Users can seamlessly switch between two distinct chat environments, each tailored to specific functionalities.