Certainly! Below is the modified code that sets up a Gradio application with two tabs:
- LLaMa 3.2 Vision: Allows you to chat with the LLaMa 3.2 Vision model and upload images.
- LLaMa 3.1 with Tools: Allows you to chat with the LLaMa 3.1 model, which has access to a web search tool and an image generation tool that uploads
image.png to the chat.
Here's the complete code:
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
@tool
def generate_image(prompt: str) -> str:
"""Generates an image based on the prompt and returns a base64 encoded image."""
# For demo purposes, we will load image.png and return it
image_path = 'image.png'
if os.path.exists(image_path):
image = Image.open(image_path)
buffered = BytesIO()
image.save(buffered, format="PNG")
img_b64 = base64.b64encode(buffered.getvalue()).decode("utf-8")
return f""
else:
return "Image not found."
# Initialize the models
# llama3.2-vision for image inputs (does not support tools)
llm_image = ChatOllama(
model='llama3.2-vision',
temperature=0.8,
# Other parameters as needed
)
# llama3.1 with tool calling capabilities for text inputs
llm_text = ChatOllama(
model='llama3.1',
temperature=0.8,
# 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="JPEG")
img_str = base64.b64encode(buffered.getvalue()).decode("utf-8")
return img_str
def chatbot_image(message, history):
# This function handles chat with llama3.2-vision
# message can be text and/or image
# history is a list of tuples (user_message, bot_message)
# Prepare the conversation history for the model
model_messages = []
# Convert history to the format expected by the model
for user_msg, bot_msg in history:
# Handle user's previous messages
user_content_parts = []
if isinstance(user_msg, dict):
if user_msg.get("text") and user_msg.get("text").strip() != "":
user_content_parts.append({"type": "text", "text": user_msg["text"]})
if user_msg.get("image"):
image_b64 = convert_image_to_base64(user_msg["image"])
user_content_parts.append({
"type": "image_url",
"image_url": f"data:image/jpeg;base64,{image_b64}",
})
else:
if isinstance(user_msg, str) and user_msg.strip() != "":
user_content_parts.append({"type": "text", "text": user_msg})
elif isinstance(user_msg, Image.Image):
image_b64 = convert_image_to_base64(user_msg)
user_content_parts.append({
"type": "image_url",
"image_url": f"data:image/jpeg;base64,{image_b64}",
})
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):
# Handle bot's image messages if any
pass
# Handle the latest message from the user
user_content_parts = []
if isinstance(message, dict):
if message.get("text") and message.get("text").strip() != "":
user_content_parts.append({"type": "text", "text": message["text"]})
if message.get("image"):
image_b64 = convert_image_to_base64(message["image"])
user_content_parts.append({
"type": "image_url",
"image_url": f"data:image/jpeg;base64,{image_b64}",
})
elif isinstance(message, str) and message.strip() != "":
user_content_parts.append({"type": "text", "text": message})
elif isinstance(message, Image.Image):
image_b64 = convert_image_to_base64(message)
user_content_parts.append({
"type": "image_url",
"image_url": f"data:image/jpeg;base64,{image_b64}",
})
if user_content_parts:
model_messages.append(HumanMessage(content=user_content_parts))
# Generate the response using the model and stream it
response = ""
for chunk in llm_image.stream(model_messages):
if hasattr(chunk, 'content'):
response += chunk.content
yield response # Stream the response to Gradio
else:
continue
def chatbot_text(message, history):
# This function handles chat with llama3.1 and tools
# message is text
# history is a list of tuples (user_message, bot_message)
# Prepare the conversation history for the model
model_messages = []
# Include system prompt about tools
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\n"
"2. **generate_image**: Generates an image (demo image) based on the prompt and returns it.\n\n"
"Use these tools whenever appropriate to provide accurate and helpful responses."
)
model_messages.append(SystemMessage(content=system_prompt))
# Convert history to the format expected by the model
for user_msg, bot_msg in history:
# User's previous messages
if user_msg and isinstance(user_msg, str) and user_msg.strip() != "":
model_messages.append(HumanMessage(content=user_msg))
# Bot's previous messages
if bot_msg:
if isinstance(bot_msg, str):
model_messages.append(AIMessage(content=bot_msg))
elif isinstance(bot_msg, dict):
# Handle bot's image messages if any
pass
# Handle the latest message from the user
if isinstance(message, str) and message.strip() != "":
model_messages.append(HumanMessage(content=message))
# Generate the response using the model and stream it
response = ""
for chunk in llm_text.stream(model_messages):
if hasattr(chunk, 'content'):
response += chunk.content
# Check if the response contains a base64 image string and render it
if "data:image/png;base64" in response or "data:image/jpeg;base64" in response:
yield gr.update(value=response, visible=True)
else:
yield response # Stream the response to Gradio
else:
continue
# Create Gradio ChatInterface for LLaMa 3.2 Vision
chatbot_interface_image = gr.ChatInterface(
fn=chatbot_image,
multimodal=True,
title="Chat with LLaMa 3.2 Vision",
description="Chat with LLaMa 3.2 Vision. You can upload images and text."
)
# Create Gradio ChatInterface for LLaMa 3.1 with Tools
chatbot_interface_text = gr.ChatInterface(
fn=chatbot_text,
title="Chat with LLaMa 3.1 with Tools",
description="Chat with LLaMa 3.1. You can use tools like web search and image generation."
)
# Combine both interfaces into a Tabbed Interface
demo = gr.TabbedInterface(
[chatbot_interface_image, chatbot_interface_text],
["LLaMa 3.2 Vision", "LLaMa 3.1 with Tools"]
)
if __name__ == "__main__":
demo.launch()
Explanation:
-
Modules and Imports: The necessary modules and tools are imported, including Gradio, LangChain, and the tools for web search and image generation.
-
Tool Definitions:
search_web: Uses DuckDuckGo to perform web searches.
generate_image: For demo purposes, it loads image.png and returns it as a base64-encoded string.
-
Model Initialization:
llm_image: Initialized with llama3.2-vision for handling image inputs.
llm_text: Initialized with llama3.1 and bound to the tools search_web and generate_image.
-
Helper Function:
convert_image_to_base64: Converts a PIL Image to a base64-encoded string for displaying images in the chat.
-
Chatbot Functions:
chatbot_image: Handles the chat logic for the LLaMa 3.2 Vision model, capable of processing both text and image inputs.
chatbot_text: Handles the chat logic for the LLaMa 3.1 model with tool support. It interprets user messages and utilizes tools when appropriate.
-
Gradio Interfaces:
chatbot_interface_image: Gradio ChatInterface for LLaMa 3.2 Vision with multimodal support.
chatbot_interface_text: Gradio ChatInterface for LLaMa 3.1 with tool support.
-
Tabbed Interface:
demo: Combines both chat interfaces into a tabbed interface using gr.TabbedInterface.
-
Launching the App:
- The Gradio app is launched with
demo.launch().
Note: Ensure that you have an image.png file in the same directory as your script for the generate_image tool to work correctly. If it's not present, the tool will return "Image not found."
Usage:
Dependencies:
Make sure you have the necessary libraries installed:
pip install gradio
pip install langchain
pip install Pillow
# Install other dependencies as required
Note on Safety and Compliance:
- The assistant is designed to be helpful and utilize tools appropriately.
- Ensure that any content generated complies with usage policies and is appropriate for your audience.