langchain_ollama attach image to prompt

I’m expirementing with llama 3.2 vision 11B and I’m having a bit of a rough time attaching an image, wether it’s local or online, to the chat. Here’s my Python code:

import io
import base64
import requests
from PIL import Image
from langchain_ollama import OllamaLLM
from langchain_core.prompts import ChatPromptTemplate

# Define exit keywords
EXIT_KEYWORDS = ["exit", "quit", "stop", "bye", "end"]

def encode_image_to_base64(image_path: str) -> str:
    """Encodes the image at the given path to a Base64 string."""
    try:
        with open(image_path, "rb") as image_file:
            encoded_string = base64.b64encode(image_file.read()).decode("utf-8")
            return encoded_string
    except FileNotFoundError:
        print(f"Error: The file {image_path} was not found.")
        return None
    except Exception as e:
        print(f"Error: Could not process the image at {image_path}. Reason: {e}")
        return None

def fetch_image_from_url(image_url: str) -> str:
    """Fetches an image from a URL and encodes it as Base64."""
    try:
        response = requests.get(image_url)
        response.raise_for_status()  # Raise an exception for HTTP errors
        image = Image.open(io.BytesIO(response.content))
        buffered = io.BytesIO()
        image.save(buffered, format=image.format)  # Preserve original format
        return base64.b64encode(buffered.getvalue()).decode("utf-8")
    except Exception as e:
        print(f"Error: Could not fetch the image from URL. Reason: {e}")
        return None

def handle_conversation():
    """Handles the conversation loop with the user."""
    context = ""
    model = OllamaLLM(model="llama3.2-vision")
    prompt = ChatPromptTemplate.from_template("""
        Answer the question below. If an image is provided, analyze it and provide relevant information.

        Here is the conversation history: {context}

        Question: {question}

        Image (if any): {image_data}

        Answer:
    """)
    chain = prompt | model

    while True:
        user_input = input("You: ")
        if user_input.lower() in EXIT_KEYWORDS:
            print("Goodbye!")
            break
        image_data = None
        text_input = user_input.strip()

        # Check if user input includes "image:"
        if "image:" in user_input:
            try:
                text_input, image_reference = user_input.split("image:", 1)
                text_input = text_input.strip()
                image_reference = image_reference.strip()

                if image_reference.startswith("http://") or image_reference.startswith("https://"):
                    # Handle online image URL
                    image_data = fetch_image_from_url(image_reference)
                else:
                    # Handle local image path
                    image_data = encode_image_to_base64(image_reference)

                if not image_data:
                    print("Error: Unable to process the provided image.")
                    continue
            except ValueError:
                print("Error: Invalid input format. Use 'Your question here image: [path_to_image or URL]'.")
                continue

        # Invoke the model with the current context, question, and image data
        result = chain.invoke({"context": context, "question": text_input, "image_data": image_data})
        print(f"Bot: {result}")

        # Update the context with the latest user input and bot response
        context += f"nUser: {text_input}nAI: {result}"

if __name__ == "__main__":
    handle_conversation()

The lack of proper documentation makes this harder.
Any help/resources are much appreciated.

Simple text prompting works just fine. It’s the image attaching that I’m having trouble with.

New contributor

Za3tour420 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa

langchain_ollama attach image to prompt

I’m expirementing with llama 3.2 vision 11B and I’m having a bit of a rough time attaching an image, wether it’s local or online, to the chat. Here’s my Python code:

import io
import base64
import requests
from PIL import Image
from langchain_ollama import OllamaLLM
from langchain_core.prompts import ChatPromptTemplate

# Define exit keywords
EXIT_KEYWORDS = ["exit", "quit", "stop", "bye", "end"]

def encode_image_to_base64(image_path: str) -> str:
    """Encodes the image at the given path to a Base64 string."""
    try:
        with open(image_path, "rb") as image_file:
            encoded_string = base64.b64encode(image_file.read()).decode("utf-8")
            return encoded_string
    except FileNotFoundError:
        print(f"Error: The file {image_path} was not found.")
        return None
    except Exception as e:
        print(f"Error: Could not process the image at {image_path}. Reason: {e}")
        return None

def fetch_image_from_url(image_url: str) -> str:
    """Fetches an image from a URL and encodes it as Base64."""
    try:
        response = requests.get(image_url)
        response.raise_for_status()  # Raise an exception for HTTP errors
        image = Image.open(io.BytesIO(response.content))
        buffered = io.BytesIO()
        image.save(buffered, format=image.format)  # Preserve original format
        return base64.b64encode(buffered.getvalue()).decode("utf-8")
    except Exception as e:
        print(f"Error: Could not fetch the image from URL. Reason: {e}")
        return None

def handle_conversation():
    """Handles the conversation loop with the user."""
    context = ""
    model = OllamaLLM(model="llama3.2-vision")
    prompt = ChatPromptTemplate.from_template("""
        Answer the question below. If an image is provided, analyze it and provide relevant information.

        Here is the conversation history: {context}

        Question: {question}

        Image (if any): {image_data}

        Answer:
    """)
    chain = prompt | model

    while True:
        user_input = input("You: ")
        if user_input.lower() in EXIT_KEYWORDS:
            print("Goodbye!")
            break
        image_data = None
        text_input = user_input.strip()

        # Check if user input includes "image:"
        if "image:" in user_input:
            try:
                text_input, image_reference = user_input.split("image:", 1)
                text_input = text_input.strip()
                image_reference = image_reference.strip()

                if image_reference.startswith("http://") or image_reference.startswith("https://"):
                    # Handle online image URL
                    image_data = fetch_image_from_url(image_reference)
                else:
                    # Handle local image path
                    image_data = encode_image_to_base64(image_reference)

                if not image_data:
                    print("Error: Unable to process the provided image.")
                    continue
            except ValueError:
                print("Error: Invalid input format. Use 'Your question here image: [path_to_image or URL]'.")
                continue

        # Invoke the model with the current context, question, and image data
        result = chain.invoke({"context": context, "question": text_input, "image_data": image_data})
        print(f"Bot: {result}")

        # Update the context with the latest user input and bot response
        context += f"nUser: {text_input}nAI: {result}"

if __name__ == "__main__":
    handle_conversation()

The lack of proper documentation makes this harder.
Any help/resources are much appreciated.

Simple text prompting works just fine. It’s the image attaching that I’m having trouble with.

New contributor

Za3tour420 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật