Whitepaper
Docs
Sign In
Tool
Tool
vx4
Image Gen 4o Universal Applied Intelligence built by Bejo
Tool ID
image_gen_4o_universal_applied_intelligence_built_by_bejo
Creator
@ejbevan
Downloads
156+
Image Gen 4o - Universal Applied Intelligence built by Bejo
Get
README
No README available
Tool Code
Show
""" title: Image Gen 4o - Universal Applied Intelligence built by Bejo author: open-webui version: x4 """ import os import openai import base64 import re from datetime import datetime from typing import Any, Dict, Optional # Set your OpenAI API key OPENAI_API_KEY = "sk-" openai.api_key = OPENAI_API_KEY class Tools: def __init__(self): pass async def generate_image( self, prompt: str, request: Any = None, user: Optional[Dict[str, Any]] = None, __event_emitter__=None ) -> str: """ Generate an image given a prompt using OpenAI's DALL-E API. The image is both saved to disk and sent inline as HTML. """ if __event_emitter__ is None: return "Event emitter is required for this function" await __event_emitter__({ "type": "status", "data": { "description": "Generating an image with DALL-E 3", "done": False, }, }) try: # Enhance the prompt for better image quality enhanced_prompt = self._enhance_prompt(prompt) # Generate the image using OpenAI's Image API (DALL-E) response = openai.Image.create( prompt=enhanced_prompt, n=1, size="1024x1024", response_format="b64_json" ) # Extract image data image_data = response["data"][0]["b64_json"] # Create a timestamped filename for uniqueness timestamp = datetime.now().strftime("%Y%m%d%H%M%S") image_filename = f"image_{timestamp}.png" # Determine save path and ensure directory exists save_dir = os.path.join("static", "generated_images") os.makedirs(save_dir, exist_ok=True) save_path = os.path.join(save_dir, image_filename) # Save the image to disk with open(save_path, "wb") as f: f.write(base64.b64decode(image_data)) # Generate URL for the saved image (if needed) image_url = f"/static/generated_images/{image_filename}" await __event_emitter__({ "type": "status", "data": { "description": "Image successfully generated", "done": True, }, }) # Send inline HTML with the generated image and prompt details await __event_emitter__({ "type": "message", "data": { "content": ( f"<div style='text-align:center; margin:20px 0;'>" f"<img src='data:image/png;base64,{image_data}' alt='Generated Image' style='max-width:100%;' />" f"</div>\n\n" f"**Original Prompt:** {prompt}\n\n" f"**Enhanced Prompt:** {enhanced_prompt}" ) }, }) return "Image has been successfully generated" except Exception as e: print(f"Error in image generation: {str(e)}") await __event_emitter__({ "type": "status", "data": {"description": f"An error occurred: {str(e)}", "done": True}, }) await __event_emitter__({ "type": "message", "data": { "content": ( f"**Error generating image:** {str(e)}\n\n" f"Please try again with a different prompt or contact support if the issue persists." ) }, }) return f"Error: {str(e)}" def _enhance_prompt(self, prompt: str) -> str: """ Enhance the prompt to improve image quality by adding quality terms if not already present. """ # Remove any backticks from the prompt clean_prompt = re.sub(r'`([^`]+)`', r'\1', prompt) # Check for existing quality terms in the prompt has_quality_terms = any( term in clean_prompt.lower() for term in ["high quality", "detailed", "professional", "4k", "hd"] ) # Append quality enhancements if not already present if not has_quality_terms: return f"{clean_prompt}, high quality, detailed, professional lighting, cinematic, 4k" else: return clean_prompt