# How to make an image tool?

**URL:** <https://forum.langchain.com/t/how-to-make-an-image-tool/339>\
**Category:** LangChain\
**Tags:** python-help\
**Created:** [July 9, 2025, 7:28am UTC](https://forum.langchain.com/t/how-to-make-an-image-tool/339 "2025-07-09T07:28:50Z")\
**Posts on this page:** 12\
**Page:** 1

<div class="post-metadata">

**Author:** ![hottered10](https://yyz1.discourse-cdn.com/flex007/user_avatar/forum.langchain.com/hottered10/32/119_2.png) [@hottered10](https://forum.langchain.com/u/hottered10)\
**Post date:** [July 9, 2025, 7:28am UTC](https://forum.langchain.com/t/how-to-make-an-image-tool/339/1 "2025-07-09T07:28:50Z")

</div>

How can i create a tool, which will allow agent to read and understand the image, What should the tool return so that agent can read the image or any other binary formats. Note that i don’t want to make the tool which describes the image, instead i want to create the tool which will allow agents to read the image/images?

---

<div class="post-metadata">

**Author:** ![marco](https://avatars.discourse-cdn.com/v4/letter/m/a698b9/32.png) [@marco](https://forum.langchain.com/u/marco)\
**Post date:** [July 9, 2025, 9:10am UTC](https://forum.langchain.com/t/how-to-make-an-image-tool/339/2 "2025-07-09T09:10:19Z")

</div>

Hi @hottered10 ! Correct me if I’m wrong but you are trying to create a tool that takes as input an image (by url or file path) and returns some data for the agent to comprehend.  
Usually, you can call a multimodal model by passing a message that specifies the file format and the source type (check the [Multimodality guide](https://python.langchain.com/docs/concepts/multimodality/)). By appending multiple messages you can not only textually describe the image but also providing a more [structured output](https://python.langchain.com/docs/concepts/structured_outputs/) for the main agent to digest.

Inside your tool you’ll still need a way to process that image (by using an llm or a more traditional method).  
Let me know if this helped!

---

<div class="post-metadata">

**Author:** ![rako](https://yyz1.discourse-cdn.com/flex007/user_avatar/forum.langchain.com/rako/32/121_2.png) [@rako](https://forum.langchain.com/u/rako)\
**Post date:** [July 9, 2025, 11:03am UTC](https://forum.langchain.com/t/how-to-make-an-image-tool/339/3 "2025-07-09T11:03:44Z")

</div>

I came across a similar problem, and I only found tools that describe images by returning a string. I want my agent to be able to recognize when an image contains a table and understand its contents, or for an example it’s an image of nature, to recognize the objects in it, not just receive a descriptive string from a tool.

---

<div class="post-metadata">

**Author:** ![marco](https://avatars.discourse-cdn.com/v4/letter/m/a698b9/32.png) [@marco](https://forum.langchain.com/u/marco)\
**Post date:** [July 9, 2025, 12:36pm UTC](https://forum.langchain.com/t/how-to-make-an-image-tool/339/4 "2025-07-09T12:36:02Z")

</div>

Hey @rako and @hottered10 you could do something similar to the following:

```python
from pydantic import BaseModel, Field
from langchain_openai import ChatOpenAI
from langchain_core.messages import SystemMessage, HumanMessage
from langchain_core.tools import tool

class ImageInfo(BaseModel):
    description: str = Field(description="A description of the image")
    table: bool = Field(description="Whether there is a table in the image")
    table_content: str = Field(description="The content of the table if there is one")

llm = ChatOpenAI(model="gpt-4o-mini")
structured_llm = llm.with_structured_output(ImageInfo)

@tool
def extract_image_info(image_url: str) -> dict:
    """
    Extracts structured information from an image given the following output schema:
    - description: A description of the image
    - table: Whether there is a table in the image
    - table_content: The content of the table if there is one

    Args:
        image_url: The URL of the image to analyze

    Returns:
        A dictionary containing the description, table, and table content
    """

    
    response = structured_llm.invoke([
        SystemMessage(content="You are a helpful assistant that extracts structured information from an image."),
        HumanMessage(
            content=[
                {"type": "text", "text": "Analyze the image"},
                {
                    "type": "image",
                    "source_type": "url",
                    "url": image_url,
                },
            ],
        )
    ])
    return response.model_dump()

```

This is a possible solution to your problem, then it’s up to the ability of the model to comprehend tables in images. Inside the tool you could make more complex operations like splitting the image in multiple chunks, analyze each one of them and merge the results together. You could use a computer vision model to detect tables/object in images etc

---

<div class="post-metadata">

**Author:** ![chester-lc](https://avatars.discourse-cdn.com/v4/letter/c/71c47a/32.png) [@chester-lc](https://forum.langchain.com/u/chester-lc)\
**Post date:** [July 9, 2025, 1:59pm UTC](https://forum.langchain.com/t/how-to-make-an-image-tool/339/5 "2025-07-09T13:59:22Z")

</div>

You can generally create ToolMessages containing an image content block, e.g.,

```python
ToolMessage(
    content=[
        {
            "type": "image",
            "source_type": "base64",
            "data": image_data,
            "mime_type": "image/jpeg",
        },
    ],
    tool_call_id="...",
)

```

The above format is LangChain’s cross-provider standard. Providers also support OpenAI format:

```python
ToolMessage(
    content=[
        {
            "type": "image_url",
            "image_url": {"url": f"data:image/jpeg;base64,{image_data}"},
        },
    ],
    tool_call_id="...",
)

```

Note that not all LLM providers support this functionality. I believe Anthropic and Gemini both do.

This is admittedly not documented well, but is described in the [docs for a standard test](https://python.langchain.com/api_reference/standard_tests/integration_tests/langchain_tests.integration_tests.chat_models.ChatModelIntegrationTests.html#langchain_tests.integration_tests.chat_models.ChatModelIntegrationTests.test_image_tool_message) we run on select models supporting this feature.

---

<div class="post-metadata">

**Author:** ![rako](https://yyz1.discourse-cdn.com/flex007/user_avatar/forum.langchain.com/rako/32/121_2.png) [@rako](https://forum.langchain.com/u/rako)\
**Post date:** [July 10, 2025, 6:50am UTC](https://forum.langchain.com/t/how-to-make-an-image-tool/339/6 "2025-07-10T06:50:29Z")

</div>

Hello @marco and @chester-lc! Thank you for the help, I’ll try the suggestions you sent me, and if you think of anything else, please send it my way 🙂

---

<div class="post-metadata">

**Author:** ![Papadopulus](https://yyz1.discourse-cdn.com/flex007/user_avatar/forum.langchain.com/papadopulus/32/140_2.png) [@Papadopulus](https://forum.langchain.com/u/Papadopulus)\
**Post date:** [July 10, 2025, 9:08am UTC](https://forum.langchain.com/t/how-to-make-an-image-tool/339/7 "2025-07-10T09:08:39Z")

</div>

@chester-lc Thanks for the help. I tried test exaple from LangChain you referenced. Here is the code:

```auto
import base64
from langchain_core.messages import HumanMessage, ToolMessage, AIMessage
from langchain_openai import ChatOpenAI

def random_image() -> dict:
    "Return a image"
    return ""

llm = ChatOpenAI(
    model="gpt-4.1-2025-04-14", # make sure your API key supports this
    temperature=0,
)
image_path = "/home/bogdan/Desktop/banana.jpeg"
with open(image_path, "rb") as image_file:
    image_data = base64.b64encode(image_file.read()).decode("utf-8")

tool_message = ToolMessage(
    content=[
        {
            "type": "image_url",
            "image_url": {"url": f"data:image/jpeg;base64,{image_data}"},
        },
    ],
    tool_call_id="1",
    name="random_image",
)

messages = [
    HumanMessage(
        content=[{"type": "text", "text": "Can you load the image and describe it?"}]
    ),
    AIMessage(
        [],
        tool_calls=[
            {
                "type": "tool_call",
                "id": "1",
                "name": "random_image",
                "args": {},
            }
        ],
    ),
    tool_message,
]

response = llm.bind_tools([random_image]).invoke(messages)

print(response)

```

But i got this AIMessage as response:

```auto
response = AIMessage(content='It appears that no image has been uploaded or provided yet. Please upload an image or provide a link, and I’ll be happy to describe it for you!',...)

```

I also tried to call tool which returns this type of dictionary:

```auto
{
   "type": "image_url",
   "image_url": {"url": f"data:image/jpeg;base64,{encoded_image}"},
}

```

```auto
@tool
def image_tool(input: str) -> dict:
    """This is tool for loading image"""
    file_path = "/home/bogdan/Desktop/banana.jpeg"
    with open(file_path, "rb") as f:
        image_data = f.read()
    encoded_image = base64.b64encode(image_data).decode("utf-8")
    return {
        "type": "image_url",
        "image_url": {"url": f"data:image/jpeg;base64,{encoded_image}"},
    }

llm = ChatOpenAI(model="gpt-4o", temperature=0)

agent = initialize_agent(
    tools=[image_tool],
    llm=llm,
    agent="zero-shot-react-description",
    verbose=True,
    handle_parsing_errors=True,
)

response = agent.invoke(
    {"input": "Can you load the image and tell me what is on the picture?"}
)

print(response)

```

But i got this response:

```auto
Thought:The image has been successfully loaded, and it appears to be a complex scene with various elements. However, I cannot directly interpret or describe the contents of the image from the base64 data provided. You may need to use an image viewer to see the image or provide a description of what you see.
Observation: Invalid Format: Missing 'Action:' after 'Thought:
Thought:I cannot directly interpret or describe the contents of the image from the base64 data provided. You may need to use an image viewer to see the image or provide a description of what you see.

```

Do you know any other solution where agent will know that return type contains image and know how to process it? Thanks again.

---

<div class="post-metadata">

**Author:** ![chester-lc](https://avatars.discourse-cdn.com/v4/letter/c/71c47a/32.png) [@chester-lc](https://forum.langchain.com/u/chester-lc)\
**Post date:** [July 10, 2025, 2:25pm UTC](https://forum.langchain.com/t/how-to-make-an-image-tool/339/8 "2025-07-10T14:25:47Z")

</div>

OpenAI does not support images in tool responses. Refer to their [API reference](https://platform.openai.com/docs/api-reference/chat/create#chat-create-messages):

 ![Screenshot 2025-07-10 at 10.22.31 AM](https://canada1.discourse-cdn.com/flex007/uploads/langchain/original/1X/fbcab251a58d2ea0293db5a2e282bed753b460d9.png)

The same appears true for their Responses API. One option is to instead use [structured outputs](https://python.langchain.com/docs/how_to/structured_output/) to generate your tool payload, and then return the response as a user message instead of a tool message:

```python
import base64
from langchain.chat_models import init_chat_model
import httpx
from pydantic import BaseModel

image_url = "https://upload.wikimedia.org/wikipedia/commons/thumb/d/dd/Gfp-wisconsin-madison-the-nature-boardwalk.jpg/2560px-Gfp-wisconsin-madison-the-nature-boardwalk.jpg"
image_data = base64.b64encode(httpx.get(image_url).content).decode("utf-8")

class GetImage(BaseModel):
    """Generate a query to fetch an image."""
    query: str

llm = init_chat_model("openai:gpt-4.1")

input_message = {"role": "user", "content": "Retrieve an image of a boardwalk."}
response = llm.invoke([input_message], response_format=GetImage)

parsed = response.additional_kwargs["parsed"]
assert isinstance(parsed, GetImage)
print(f"Fetching image: {parsed.query}")

image_message = {
    "role": "user",
    "content": [
        {
            "type": "image_url",
            "image_url": {"url": f"data:image/jpeg;base64,{image_data}"},
        }
    ]
}

llm.invoke(
    [input_message, response, image_message]
)

```

---

<div class="post-metadata">

**Author:** ![khan08pathan](https://avatars.discourse-cdn.com/v4/letter/k/e8c25b/32.png) [@khan08pathan](https://forum.langchain.com/u/khan08pathan)\
**Post date:** [February 12, 2026, 7:40pm UTC](https://forum.langchain.com/t/how-to-make-an-image-tool/339/9 "2026-02-12T19:40:33Z")

</div>

On that note, I’ve actually created a small **[Image Tool](https://easeconverter.com/)** that helps with quick tasks like converting and optimizing images without unnecessary features. If you’re into lightweight, practical tools, you can check it out — I’d genuinely love feedback.

---

<div class="post-metadata">

**Author:** ![Bandarakesh](https://yyz1.discourse-cdn.com/flex007/user_avatar/forum.langchain.com/bandarakesh/32/2991_2.png) [@Bandarakesh](https://forum.langchain.com/u/Bandarakesh)\
**Post date:** [May 11, 2026, 3:31pm UTC](https://forum.langchain.com/t/how-to-make-an-image-tool/339/10 "2026-05-11T15:31:31Z")

</div>

@Papadopulus I am running into the same problem, its because langchain ToolMessage is treating the output of the tool as string, even if the tool returns JSON it concatenating putting it under content of ToolMessage, which is making llm to see it as a text rather than a Image. I tried with the base64, it doesnt work either.

---

<div class="post-metadata">

**Author:** ![keenborder786](https://yyz1.discourse-cdn.com/flex007/user_avatar/forum.langchain.com/keenborder786/32/1757_2.png) [@keenborder786](https://forum.langchain.com/u/keenborder786)\
**Post date:** [May 11, 2026, 5:36pm UTC](https://forum.langchain.com/t/how-to-make-an-image-tool/339/11 "2026-05-11T17:36:49Z")

</div>

@Bandarakesh @Papadopulus You can use response API which does support image data in Tool Message:

```python
from langchain_openai import ChatOpenAI
from langchain_core.tools import tool
import base64, httpx

@tool
def get_image() -> list:
    """Fetch and return an image."""
    image_data = base64.b64encode(httpx.get("https://example.com/image.jpg").content).decode("utf-8")
    return [
        {
            "type": "image_url",
            "image_url": {"url": f"data:image/jpeg;base64,{image_data}"}
        }
    ]

# Key: use_responses_api=True enables image support in tool outputs
model = ChatOpenAI(model="gpt-4.1", use_responses_api=True) 
model_with_tools = model.bind_tools([get_image])

```

[OpenAI Doc reference](https://developers.openai.com/api/reference/resources/responses#(resource)%20responses%20%3E%20(model)%20response_input_image_content%20%3E%20(schema))

---

<div class="post-metadata">

**Author:** ![Taha0229](https://yyz1.discourse-cdn.com/flex007/user_avatar/forum.langchain.com/taha0229/32/3125_2.png) [@Taha0229](https://forum.langchain.com/u/Taha0229)\
**Post date:** [June 9, 2026, 9:54pm UTC](https://forum.langchain.com/t/how-to-make-an-image-tool/339/12 "2026-06-09T21:54:07Z")

</div>

Thanks for the solution, this helped, been trying to solve the problem for last 2 hours.
