Extending LLM Agents with Tools and Subagents: Implementing Text-to-Image Capabilities

    This article explains how to extend large language model (LLM) agents with text-to-image capabilities using two approaches: registering an image generation tool directly with the main agent, or wrapping the capability in a subagent for task delegation. It covers tool design, parameter and return-value conventions, agent registration, service startup, subagent architecture, a comparison of both approaches, and engineering recommendations for security, filesystem isolation, observability, cost control, and input validation.

    1. Background and Overall Approach

    The core capability of an agent built on a large language model is “reasoning plus acting”: the model understands tasks and plans steps, while concrete capability extensions rely on external tools or subagents. In real business scenarios, language generation alone is often insufficient. For example, a user may want an agent not only to describe an image but also to actually generate and save it. This requires integrating text-to-image capability into the agent.

    There are usually two implementation paths:

    1. Tool form: Wrap the text-to-image model as a tool function, register it with the main agent, and let the model decide during reasoning when to call it.
    2. Subagent form: Wrap the text-to-image capability as an independent subagent. The main agent handles task assignment and result aggregation, which is suitable for more complex multi-step tasks.

    The following sections explain each approach.

    2. Text-to-Image as a Tool

    2.1 Design Approach

    Tools are the most direct way to extend agent capabilities. A typical text-to-image tool needs to do three things:

    1. Receive a textual description of the image as an input parameter.
    2. Call the text-to-image model API and obtain the download URL of the generated result.
    3. Download the result, write it into the agent’s filesystem, and return the execution status.

    The key point here is that agent frameworks usually provide a virtual filesystem as backend storage. Images generated by the tool need to be uploaded to this virtual filesystem so that the main agent can continue to operate on these files later, such as calling other tools to process them.

    2.2 Tool Definition Example

    In a common agent development framework, tools are generally defined through decorators. The type annotations and docstring of the function signature are parsed by the framework into the tool parameter specification, helping the large model understand how to pass parameters:

    1. from langchain_core.tools import tool
    2. from openai import OpenAI
    3. import requests
    4. @tool(parse_docstring=True)
    5. def image_gen_tool(input_desc: str, output_dir: str, filename: str) -> str:
    6. """Tool for generating image from text.
    7. Args:
    8. input_desc: Description text of the image to be generated.
    9. output_dir: Directory in the virtual filesystem, starting with '/'.
    10. filename: File name of the generated image without suffix.
    11. """
    12. client = OpenAI(
    13. api_key="YOUR_API_KEY",
    14. base_url="https://api.your-provider.com/v1",
    15. )
    16. response = client.images.generate(
    17. model="text-to-image-model",
    18. prompt=input_desc,
    19. size="1024x1024",
    20. n=1,
    21. )
    22. # Extract the returned image URL
    23. url = response.images[0]['url']
    24. # Download the image
    25. resp = requests.get(url)
    26. if resp.status_code == 200:
    27. # Upload to the virtual filesystem
    28. my_backend.upload_files([(f"{output_dir}/{filename}.png", resp.content)])
    29. return f"Successfully generated and saved image to {output_dir}/{filename}.png"
    30. else:
    31. return f"Failed to generate or save image. Status code: {resp.status_code}"

    2.3 Implementation Details

    • Parameter design: input_desc carries the image description and is the natural-language input during model reasoning. output_dir and filename control the output location. Make sure to constrain paths to start with the root directory to avoid path traversal issues.
    • Docstring as prompt: The framework parses the docstring into the tool description. The clearer it is written, the more accurately the model will pass parameters when calling the tool. It is recommended to explicitly state constraints such as “the directory must start with /“ and “the filename must not include a suffix.”
    • Return-value convention: The tool’s return value is passed back to the large model for the next reasoning round. Therefore, it should return clearly structured status information, such as a success path or failure reason, rather than returning binary data directly.
    • Exception handling: In production environments, add timeout control, retry mechanisms, and parameter validation. For example, limit the length of description text and provide fallback messages when downloads fail.

    2.4 Registering the Tool and Starting the Service

    After defining the tool, register it in the agent creation function:

    1. agent = create_deep_agent(
    2. model=agent_model,
    3. system_prompt=INSTRUCTIONS,
    4. tools=[image_gen_tool],
    5. backend=my_backend,
    6. middleware=[shell_middleware],
    7. )

    Then start the agent service, using a common local development method as an example:

    1. langgraph dev --allow-blocking --host 0.0.0.0

    After the service starts, you can connect to it through a compatible chat debugging interface, such as a common community agent chat UI component, for verification. When a user asks, “Help me generate an image describing…”, the agent will autonomously call image_gen_tool. The generated image is ultimately saved in the virtual filesystem rooted at /fs, and the user can view the result in the interface.

    3. Text-to-Image as a Subagent

    3.1 Why Subagents Are Needed

    As task complexity increases, for example, “first retrieve materials, then write image captions, then generate images and summarize them into a report,” having a single agent carry all tools can lead to:

    • Excessively long context and diluted model attention.
    • Too many tools and a higher error rate in tool selection.
    • Blurred responsibility boundaries and debugging difficulties.

    The subagent architecture addresses these problems through divide-and-conquer: the main agent handles overall planning and task assignment, while each subagent focuses on one type of capability, such as a dedicated image generation subagent, with its own independent prompt, toolset, and file space.

    3.2 Implementation

    In frameworks that support the Deep Agent pattern, you can usually declare the subagents parameter directly when creating the main agent:

    1. image_agent = {
    2. "name": "image-generation-agent",
    3. "description": "Responsible for generating images from text descriptions and saving them to the specified directory",
    4. "system_prompt": "You are an image generation assistant. Receive an image description and save path, call the tool to generate the image, and return the result.",
    5. "tools": [image_gen_tool],
    6. }
    7. agent = create_deep_agent(
    8. model=agent_model,
    9. system_prompt=INSTRUCTIONS,
    10. tools=[],
    11. backend=my_backend,
    12. subagents=[image_agent],
    13. )

    During reasoning, the main agent determines whether to delegate the image generation task based on the subagent’s description, and aggregates the results after the subagent completes.

    3.3 Comparison of the Two Approaches

    Dimension Tool Form Subagent Form
    Implementation cost Low; register directly Medium; requires designing subagent prompts and boundaries
    Suitable scenarios Single, well-defined capability extension Complex multi-step tasks and capability composition
    Context management All intermediate results enter the main context Subagent has an independent context with good isolation
    Maintainability Main agent burden increases as tools grow Clear responsibilities and easier independent iteration

    In practice, the recommendation is: use the tool form when the capability is simple and call frequency is low; use the subagent form when the task chain is long and independent prompt tuning is required. The two approaches can also be combined.

    4. Engineering Recommendations

    1. Secret security: Do not hardcode API keys in code. Use environment variables or a secret management service.
    2. Filesystem isolation: Allocate independent virtual directories for different sessions to prevent concurrent tasks from overwriting each other’s files.
    3. Observability: Record the input parameters, latency, and result status of each tool call to help diagnose generation failures.
    4. Cost control: Text-to-image calls usually have quantifiable costs. Introduce caching to reuse existing results for requests with identical descriptions.
    5. Security validation: Perform content compliance checks on user-provided description text and normalize output file paths.

    5. Conclusion

    Extending an LLM agent with text-to-image capability is essentially a process of “tool encapsulation plus framework integration”: the tool form is lightweight and direct, suitable for rapid validation; the subagent form offers better isolation and is suitable for long-term evolution of complex tasks. Whichever approach you choose, clear tool documentation, well-defined return values, reliable filesystem integration, and robust exception handling are key to stable agent operation. Once developers master this methodology, they can follow the same pattern to integrate retrieval, code execution, speech synthesis, and other capabilities into agents, gradually building full-featured agent applications.