Skip to main content
Glama

generate-and-save-image

Generate custom images using FLUX AI and save them as PNG files for use in PowerPoint presentations. Provide a text prompt and filename to create visual content.

Instructions

Generates an image using a FLUX model and save the image to the specified path. The tool will return a PNG file path. It should be used when the user asks to generate or create an image or a picture.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
promptYesDescription of the image to generate in the form of a prompt.
file_nameYesFilename of the image. Include the extension of .png

Implementation Reference

  • Registration of the 'generate-and-save-image' tool in the @server.list_tools() handler, including name, description, and input schema definition.
    types.Tool(
        name="generate-and-save-image",
        description="Generates an image using a FLUX model and save the image to the specified path. The tool "
                    "will return a PNG file path. It should be used when the user asks to generate or create an "
                    "image or a picture.",
        inputSchema={
            "type": "object",
            "properties": {
                "prompt": {
                    "type": "string",
                    "description": "Description of the image to generate in the form of a prompt.",
                },
                "file_name": {
                    "type": "string",
                    "description": "Filename of the image. Include the extension of .png",
                },
            },
            "required": ["prompt", "file_name"],
        },
    ),
  • Dispatch handler logic within @server.call_tool(): validates arguments, sanitizes file path, invokes VisionManager, and returns success/error text content.
    elif name == "generate-and-save-image":
        prompt = arguments.get("prompt")
        file_name = arguments.get("file_name")
        try:
            safe_file_path = sanitize_path(folder_path, file_name)
        except ValueError as e:
            raise ValueError(f"Invalid file path: {str(e)}")
    
        if not all([prompt, file_name]):
            raise ValueError("Missing required arguments")
    
        try:
            saved_path = await vision_manager.generate_and_save_image(prompt, str(safe_file_path))
            return [
                types.TextContent(
                    type="text",
                    text=f"Successfully generated and saved image to: {saved_path}"
                )
            ]
        except Exception as e:
            return [
                types.TextContent(
                    type="text",
                    text=f"Failed to generate image: {str(e)}"
                )
            ]
  • Primary tool execution logic in VisionManager class: generates image using FLUX model via Together AI, downloads with requests, opens with PIL, and saves to disk.
    async def generate_and_save_image(self, prompt: str, output_path: str) -> str:
        """Generate an image using Together AI/Flux Model and save it to the specified path."""
    
        api_key = os.environ.get('TOGETHER_API_KEY')
        if not api_key:
            raise ValueError("TOGETHER_API_KEY environment variable not set.")
    
        client = Together(api_key=api_key)
    
        try:
            # Generate the image
            response = client.images.generate(
                prompt=prompt,
                width=1024,
                height=1024,
                steps=4,
                model="black-forest-labs/FLUX.1-schnell-Free",
                n=1,
            )
        except Exception as e:
            raise ValueError(f"Failed to generate image: {str(e)}")
    
        image_url = response.data[0].url
    
        # Download the image
        try:
            response = requests.get(image_url)
            if response.status_code != 200:
                raise ValueError(f"Failed to download generated image: HTTP {response.status_code}")
        except requests.RequestException as e:
            raise ValueError(f"Network error downloading image: {str(e)}")
    
        # Save the image
        try:
            image = Image.open(BytesIO(response.content))
            # Ensure the save directory exists
            try:
                os.makedirs(os.path.dirname(output_path), exist_ok=True)
            except OSError as e:
                raise ValueError(f"Failed to create a directory for image: str({e})")
            # Save the image
            image.save(output_path)
        except (IOError, OSError) as e:
            raise ValueError(f"Failed to save image to {output_path}: {str(e)}")
    
        return output_path

Latest Blog Posts

MCP directory API

We provide all the information about MCP servers via our MCP API.

curl -X GET 'https://glama.ai/api/mcp/v1/servers/supercurses/powerpoint'

If you have feedback or need assistance with the MCP directory API, please join our Discord server